|
|
|
|
|
|
|
Overloading Constructors. |
|
|
|
|
|
|
|
|
A constructor is used to create an object. For example, the Rectangle constructor creates 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 capability 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. The compiler chooses the right constructor just as it does any overloaded function: based on the number and type of the parameters. |
|
|
|
|
|
|
|
|
While you can overload constructors, you cannot overload destructors. Destructors, by definition, always have exactly the same signature: the name of the class prepended by a tilde (~) and no parameters. |
|
|
|
|
|
|
|
|
Up until now, you've been setting the member variables of objects in the body of the constructor. Constructors, however, are created in two stages: the initialization stage and then the body of the constructor. |
|
|
|
|
|
|
|
|
Most variables can be set in either stage, either by initializing in the initialization stage or by assigning in the body of the constructor. It is cleaner and often more efficient to initialize member variables at the initialization stage. The following example shows how to initialize member variables: |
|
|
|
|
|
|
|
|
CAT(): // constructor name and parameters
itsAge(5), // initialization list
itsWeight(8)
{} // body of constructor |
|
|
|
|
|
|
|
|
After the closing parentheses on the constructor's parameter list, put a colon. Then put the name of the member variable and a pair of parentheses. Inside the parentheses, put the expression to be used to initialize that member variable. If there is more than one initialization, separate each one with a comma. |
|
|
|
|
|
|
|
|
Remember that references and constants must be initialized and cannot be assigned to. If you have references or constants as member data, these must be initialized as shown here. |
|
|
|
|
|
|
|
|
Earlier, I said it is more efficient to initialize member variables rather than to assign to them. To understand this, you must first understand the copy constructor. |
|
|
|
|
|