21: itsWidth = 5;
22: itsLength = 10;
23: }
24:
25: Rectangle::Rectangle (int width, int length)
26: {
27: itsWidth = width;
28: itsLength = length;
29: }
30:
31: int main()
32: {
33: Rectangle Rect1;
34: cout << “Rect1 width: “ << Rect1.GetWidth() << endl;
35: cout << “Rect1 length: “ << Rect1.GetLength() << endl;
36:
37: int aWidth, aLength;
38: cout << “Enter a width: “;
39: cin >> aWidth;
40: cout << “\nEnter a length: “;
41: cin >> aLength;
42:
43: Rectangle Rect2(aWidth, aLength);
44: cout << “\nRect2 width: “ << Rect2.GetWidth() << endl;
45: cout << “Rect2 length: “ << Rect2.GetLength() << endl;
46: return 0;
47: }
Rect1 width: 5
Rect1 length: 10
Enter a width: 20
Enter a length: 50
Rect2 width: 20
Rect2 length: 50
The Rectangleclass is declared on lines 6–17. Two constructors are declared:
the “default constructor” on line 9 and a second constructor on line 10, which
takes two integer variables.
On line 33, a rectangle is created using the default constructor, and its values are printed
on lines 34 and 35. On lines 38–41, the user is prompted for a width and length, and the
constructor taking two parameters is called on line 43. Finally, the width and height for
this rectangle are printed on lines 44 and 45.
Just as it does any overloaded function, the compiler chooses the right constructor, based
on the number and type of the parameters.
OUTPUT
296 Day 10
LISTING10.3 continued
ANALYSIS