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

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.