|

The
point of a constructor is to establish the object;
for example, the point of a Rectangle constructor
is to make a rectangle. Before the constructor runs,
there is no rectangle, just an area of memory. After
the constructor finishes, there is a complete, ready-to-use
rectangle object.
Constructors,
like all member functions, can be overloaded. The
ability to overload constructors is very powerful
and very flexible.
For
example, you might have a rectangle object that
has two constructors: The first takes a length and
a width and makes a rectangle of that size. The
second takes no values and makes a default-sized
rectangle. Listing 10.3 implements this idea.
Listing
10.3. Overloading the constructor.
1:
// Listing 10.3
2:
// Overloading constructors
3:
4:
#include <iostream.h>
5:
6:
class Rectangle
7:
{
8:
public:
9:
Rectangle();
10:
Rectangle(int width, int length);
11:
~Rectangle() {}
12:
int GetWidth() const { return itsWidth; }
13:
int GetLength() const { return itsLength; }
14:
private:
15:
int itsWidth;
16:
int itsLength;
17:
};
18:
19:
Rectangle::Rectangle()
20:
{
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:
}
OUTPUT:
Rect1 width: 5
Rect1 length: 10
Enter a width: 20
Enter a length: 50
Rect2 width: 20
Rect2 length: 50
ANALYSIS: The Rectangle class is declared
on lines 6-17. Two constructors are declared: the
"default constructor" on line 9 and a constructor
taking two integer variables.
On
line 33, a rectangle is created using the default
constructor, and its values are printed on lines
34-35. On lines 37-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-45.
Just
as it does any overloaded function, the compiler
chooses the right constructor, based on the number
and type of the parameters.
|