O'Reilly logo

Sams Teach Yourself C++ in 24 Hours, Third Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required