Professional Documents
Culture Documents
Constructor
Example:
class Date
{
public:
Date(); // constructor
~Date(); // destructor
…
};
public:
Date() // default constructor
{ day = 1; month = 1; year = 2000;}
Date (int d, int m, int y); // parameterized constructor
void setYear(int y);
void setMonth(int m);
void setDay(int d);
void show(); // displays date
};
W03- Classes and Objects
29
Class Implementation
void Date::setDay (int d)
{
day = d; }
void Date::show()
{
cout <<day << ”-” <<month << ”-” <<year<< endl;
}
Copy Constructor
The copy constructor initializes an object with
another object of the same class.
Example:
void main()
{
Date d1(12,4,1997);
Date d2(d1); // default copy constructor
Date d3=d1; // default copy constructor
}
Time t1(4,23,45);
cout << endl << “Universal time is ";
t.printUniversal();
cout << endl << "Standard time is ";
t.printStandard();
return 0;
}
Rectangle
length
width
setLength()
setWidth()
getLength()
getWidth()
getArea()
Rectangle
Access modifiers
are denoted as: - width : double
+ public
- private
+ setWidth(w : double) : void
Function parameters
Rectangle
are shown inside the
parentheses using the
same notation as
- width : double
variables.
private:
int x,y;
};
W03- Classes and Objects
45
void Point::print() {
cout << “(” << x << “,” << y << “)”;
}
Const Objects
const specify that an object is not modifiable
Example
const Time noon( 12, 0, 0 );
int Date::addYear(int n)
{ year+=n; }
W03- Classes and Objects
48
int main () {
P x,y;
cout << x.c;
x.c = ‘A’;
cout << y.c;
}
W03- Classes and Objects
51
int main()
{ Foo f1;
Foo f2;
f1.display();
{ Foo f3;
f2.display(); }
f1.display();
return 0; }
W03- Classes and Objects
53
void showDist ( )
{ cout <<feet << “ \’ ” << inches <<“ \” “; }
int main()
{
Distance dist1,dist2;
Distance dist3(11,6.5);
dist1.getdist();
dist2 = dist1.addDist(dist3);