38

A child (derived) class gets the members of a parent (base) class, so code is reused. It models an is-a relationship: a Dog is an Animal.

Single, multilevel, multiple and hierarchical inheritance

Single, multilevel, multiple and hierarchical inheritance

C++ 13 lines
class Animal {
public:
    void eat() { cout << "Eating\n"; }
};

class Dog : public Animal {      // Dog inherits Animal
public:
    void bark() { cout << "Barking\n"; }
};

Dog d;
d.eat();    // from Animal
d.bark();   // own method

Q & A

  1. What is the diamond problem?
    In multiple inheritance, if B and C both inherit A and D inherits B and C, D gets two copies of A. C++ solves it with virtual inheritance (class B : virtual public A).
  2. Constructor call order in inheritance?
    Parent constructor runs first, then child. Destructors run in the reverse order: child first, then parent.