An instance of a derived class contains all the members of the base class, and all of those members must be initialized. Consequently, the base class's constructor has to be called by the derived class's constructor. When you write the constructor for a derived class, you must specify a “base initializer,” using syntax similar to that of the member initializer list for constructing member objects. Place a colon after the argument list of the derived class's constructor, and follow it with the name of the base class and an argument list. For example:
// Constructor function for WageEmployee
WageEmployee::WageEmployee( const char *nm )
: Employee( nm )
{
wage = 0.0;
hours = 0.0;
}
// Constructor function for SalesPerson
SalesPerson::SalesPerson( const char *nm )
: WageEmployee( nm )
{
commission = 0.0;
salesMade = 0.0;
}
// Constructor function for Manager
Manager::Manager( const char *nm )
: Employee( nm )
{
weeklySalary = 0.0;
}
When you declare an object of a derived class, the compiler executes the constructor for the base class first, and then executes the constructor for the derived class. (If the derived class contains member objects, their constructors are executed after the base class's constructor, but before the derived class's constructor.)
You can omit the base initializer if the base class has a default constructor. As with member objects, however, you should use the base initializer syntax rather than perform redundant initialization.
You can specify both a member initializer list and a base initializer if you're defining a derived class that also has member objects. However, you cannot define member initializers for member objects defined in the base class, since that would permit multiple initializations.