day20 - Object initialization: constructors 1 Initializing...

Info iconThis preview shows pages 1–8. Sign up to view the full content.

View Full Document Right Arrow Icon
    1 Object initialization:  constructors
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
    2 Initializing objects It is tedious to have to construct an object and assign values to all of its data fields manually. Point p; p.x = 3; p.y = 8; // tedious We want something more like: Point p(3, 8); // better!
Background image of page 2
    3 Constructor constructor : A special method that initializes the state of new objects as they are created. Constructor syntax: <class name >::< class name> ( <parameter(s)> ) { <statement(s)> ; } How does this differ from previous methods?
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
    4 Point  class: Version 3 In Point.h class Point { public: int x, y; Point(int initialX, int initialY); void translate(int dx, int dy); }; In Point.cpp #include "Point.h" Point::Point(int initialX, int initialY) { x = initialX; y = initialY; } // definition of translate method omitted
Background image of page 4
    5 Tracing constructor calls What happens when the following call is made? Point p1(7, 2); p1: Point(int initialX, int initialY) { x = initialX; y = initialY; } void translate(int dx, int dy) { x += dx; y += dy; } y: x: 7 2
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
    6 Uh oh! Our client code doesn’t work anymore! program.cpp:7: error: no matching function for call to 'Point::Point()' Point.h:5: note: candidates are : Point::Point(int, int) Why did it work before? If a class has no explicit constructor, the compiler gives it a default constructor with no parameters.
Background image of page 6
    7 Solution // client code #include <stdio.h> #include <math.h> #include "Point.h" int main() { Point p1(7, 2); Point p2(4, 3); // print each point printf("p1 is (%d, %d)\n", p1.x, p1.y); printf("p1's distance from origin = %lf\n", p1.distanceFromOrigin()); printf("p2 is (%d, %d)\n", p2.x, p2.y); printf("p2's distance from origin = %lf\n", p2.distanceFromOrigin());
Background image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 8
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 25

day20 - Object initialization: constructors 1 Initializing...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online