You can initialize immediate base classes and derived class members that are not inherited from base classes by specifying initializers in the constructor definition prior to the function body.
In a constructor that is not inline, include the initialization list as part of the function definition, not as part of the class declaration.
For example:
class B1 { int b; public: B1(); B1(int i) : b(i) { /* ... */ } // inline constructor }; class B2 { int b; protected: B2(); B2(int i); // noninline constructor }; // B2 constructor definition including initialization list B2::B2(int i) : b(i) { /* ...*/ } // ... class D : public B1, public B2 { int d1, d2; public: D(int i, int j) : B1(i+1), B2(), d1(i) {d2 = j;} };
If you do not explicitly initialize a base class or member
that has constructors by calling a constructor, the compiler
automatically initializes the base class or member with a default
constructor. In the above example, if you leave out the call B2()
in the constructor of class D (as shown below), a constructor
initializer with an empty expression list is automatically
created to initialize B2. The constructors for class D, shown
above and below, result in the same construction of an object of
class D.
class D : public B1, public B2 { int d1, d2; public: // call B2() generated by compiler D(int i, int j) : B1(i+1), d1(i) {d2 = j;} };
Note: You must declare base constructors with the access specifiers public or protected to enable a derived class to call them.
Constructors and Destructors
Overview
Example of Base Constructors
and Derivation
Construction Order of Derived Class
Objects
Initialization by Constructor
Constructors
Member Access
Syntax of a Constructor Initializer