Working with Advanced Functions 297
10
Initializing Objects ..............................................................................................
Up to now, you’ve been setting the member variables of objects in the body of the con-
structor. Constructors, however, are invoked in two stages: the initialization stage and the
body.
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, write a colon. Then
write the name of the member variable and a pair of parentheses. Inside the parentheses,
write the expression to be used to initialize that member variable. If more than one ini-
tialization exists, separate each one with a comma.
Listing 10.4 shows the definition of the constructors from Listing 10.3 with initialization
of the member variables in the initialization portion of the constructor rather than by
doing assignments in the body.
LISTING10.4 A Code Snippet Showing Initialization of Member Variables
1: // Listing 10.4 – Initializing Member Variables
2: Rectangle::Rectangle():
3: itsWidth(5),
4: itsLength(10)
5: {
6: }
7:
8: Rectangle::Rectangle (int width, int length):
9: itsWidth(width),
10: itsLength(length)
11: {
12: }
Listing 10.4 is just a snippet of code, so there isn’t output. Looking at the code,
line 2 starts the default constructor. As was mentioned previously, after the stan-
dard header, a colon was added. This is followed by setting default values of 5 and 10 for
itsWidthand itsLengthon lines 3 and 4.
ANALYSIS