Initializing Objects

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 followed by 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 in the initialization list above.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.20.101