OOPortal OOPortal


Constructor Functions  «Prev  Next»
Lesson 9 Constructor initializers
Objective Add a constructor, an initializer list, and a destructor

Constructor Initializer list in C++

Add a constructor, an initializer list, and a destructor to the person class you created earlier. We can also use a constructor to initialize sub-elements of an object. Constructor initializers are specified in a comma-separated list that follows the constructor parameter list and is preceded by a colon. An initializer's form is
     member name (expression list)
For example:

foo::foo(int* t):i(7), x(9.8), z(t) //initializer list
{ //other executable code follows here ....}

We will now recode the mod_int constructor so it initializes the class member v. Instead of coding the constructor like this:
mod_int::mod_int(int i = 0)
{ v = i % modulus; }

we can code it using an initializer list like this:
//Default constructor for mod_int
mod_int::mod_int(int i = 0) : v(i % modulus){}

Notice how initialization replaced assignment. In general, initialization is preferred to assignment.
It is not always possible to assign values to members in the body of the constructor. An initializer list is required, however, when a nonstatic member is either a const or a reference.
When members are themselves classes with constructors, the expression list is matched to the appropriate constructor signature to invoke the correct overloaded constructor.

Constructor Initializers - Exercise

Click the exercise link below to add a constructor, an initializer list, and a destructor to the person class you created earlier.
Constructor Initializers - Exercise



Constructor with Field Initializer List
Syntax 4.9 - Constructor with Field Initializer List

Purpose: Supply the implementation of a constructor, initializing data fields before the body of the constructor.