The constructor initializer list
You’ve seen how important it is in
C++ to guarantee proper initialization, and it’s no different during
composition and inheritance. When an object is created, the compiler guarantees
that constructors for all of its subobjects are called. In the examples so far,
all of the subobjects have default constructors, and that’s what the
compiler automatically calls. But what happens if your subobjects
don’t have default constructors, or if you want to
change a default argument in a constructor? This is a problem because the new
class constructor doesn’t have permission to access the private
data elements of the subobject, so it can’t initialize them
directly.
The solution is simple: Call the
constructor for the subobject. C++ provides a special syntax for this, the
constructor initializer
list.
The form of the constructor initializer list echoes the act of inheritance. With
inheritance, you put the base classes after a colon and before the opening brace
of the class body. In the constructor initializer list, you put the calls to
subobject constructors after the constructor argument list and a colon, but
before the opening brace of the function body. For a class MyType,
inherited from Bar, this might look like this:
MyType::MyType(int i) : Bar(i) { // ...
if Bar has a constructor that
takes a single int
argument.