Skip to the page

Inheritance and polymorphism · core

Multiple inheritance and the diamond problem

C++ lets a class have several base classes. When two bases share a common base, the derived class gets two copies of it, unless the inheritance is virtual.

The notes

What you must know

  • C++ allows multiple inheritance: class D : public B, public C. Java allows only one base class, but many interfaces.
  • Diamond: B and C both derive from A, and D derives from B and C. Without virtual inheritance, a D object holds two copies of A's members.
  • Calling an A member on a D is then ambiguous and does not compile. You can name the path, d.B::show(), but the two copies are still there.
  • Fix: virtual inheritance, class B : virtual public A and class C : virtual public A. Then D has only one A. The virtual keyword goes on B and C, not on D.
  • With a virtual base, the most derived class (D) calls A's constructor; the calls to A's constructor in B's and C's initializer lists are skipped when a D is built.
  • Virtual bases are built before the other bases.
  • Kinds of inheritance: single, multilevel, hierarchical, multiple, and hybrid (a mix, such as the diamond).
  • Prefer composition ("has a") when the relationship is not "is a": a Car has an Engine member; it is not an Engine. Inheriting several interfaces that have no data is the simplest safe use of multiple inheritance.

The red pen

Common traps: mistake → fix

  • Mistake: virtual inheritance goes on D

    Fix: it goes on the classes that derive from A (B and C).

  • Mistake: C++ forbids multiple inheritance, like Java

    Fix: C++ allows it.

  • Mistake: Writing B::show() removes the second copy of A

    Fix: it only picks one path; virtual inheritance removes the copy.

  • Mistake: Car should inherit from Engine to reuse its code

    Fix: a Car has an Engine; use a member (composition).

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the diamond problem? Draw it with class names.
  2. How does C++ solve it? How does Java avoid it?
  3. What does virtual inheritance do, and who calls the virtual base's constructor?
  4. Car and Engine: inheritance or composition?
  5. Name the kinds of inheritance.

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview