Lesson 149 +10 XP

Constructors in Derived Classes

Constructors in Derived Classes

A derived object actually contains a sub-object of the base class. Constructing it means constructing the base first, then the derived class. Order is important.

Order of construction

When a derived object is created, C++ follows these steps in order:

  1. The base class constructor runs first.
  2. Then the derived class's own initialization runs.

The base is fully built before any derived work begins.

Passing arguments to the base constructor

The derived constructor writes an initializer list after the colon, and that list can call a base constructor:

class Vehicle {
public:
  int wheels;
  Vehicle(int w) : wheels(w) { }
};

class Car : public Vehicle {
public:
  Car(int wheels) : Vehicle(wheels) { }
};

: Vehicle(wheels) passes the argument up to the base constructor, which initializes wheels for the object.

A complete program

class Vehicle {
public:
  int wheels;
  Vehicle(int w) : wheels(w) { }
};

class Car : public Vehicle {
public:
  Car(int w) : Vehicle(w) { }
};

int main() {
  Car myCar(4);
  cout << "Wheels: " << myCar.wheels;   // prints Wheels: 4
  return 0;
}

Remember

  • If the base has no default constructor and you never call one explicitly, the code won't compile.
  • The initializer list can hold both the base call and the derived class's own member initializers.
  • The base must be ready before the derived class does anything.

TL;DR

  • Base class constructors run first, derived ones after.
  • Pass base arguments through the colon list: : Vehicle(wheels).
  • The initializer list comes after the derived constructor's parentheses.
  • Both the base call and own member initializers live in one list.
  • A base with no default constructor must be called explicitly.