Lesson 146 +10 XP

Multilevel Inheritance

Multilevel Inheritance

A class can also become another class's base. When classes inherit one after another down a chain, every member travels all the way down. That is multilevel inheritance.

A chain of classes

Here are three classes, each adding its own method:

class MyGrandDad {
public:
  void grand() { cout << "grand"; }
};

class MyDad : public MyGrandDad {
public:
  void dad() { cout << "dad"; }
};

class MyChildObj : public MyDad {
public:
  void child() { cout << "child"; }
};
  • MyDad inherits from MyGrandDad, so it has grand() plus its own dad().
  • MyChildObj inherits from MyDad, so it has grand(), dad(), and its own child().

The deepest class has everything

An object of the bottom class can call members from every level of the chain:

int main() {
  MyChildObj obj;
  obj.grand();    // from MyGrandDad
  obj.dad();      // from MyDad
  obj.child();    // MyChildObj's own member
  return 0;
}

Inherited further

Each class in the chain is itself a derived class. Members are not just the direct parent's: they arrive from every earlier generation of the chain.

TL;DR

  • Multilevel inheritance chains classes: MyGrandDad -> MyDad -> MyChildObj.
  • Each class inherits from the one directly above it.
  • The deepest class has members from every level of the chain.
  • Members keep their use all the way at the bottom.
  • New layers add on top of everything already passed down.