Interview Q&A · C++ · 9 questions in this topic

Inheritance In Depth — C++ Interview Q&A

All C++ topics

Inheritance mechanics — access modes, construction order, multiple inheritance, diamond problem and virtual base classes. Part of Inheritance & Polymorphism · 213 questions in the C++ bank.

In what order are base classes and members constructed and destroyed?

Answer

Construction runs bases first (in base-specifier order), then members (in declaration order), then the derived constructor body. Destruction is the exact mirror: body, members reversed, bases reversed.

Virtual bases are constructed before all non-virtual bases by the most-derived class, which is how the diamond shares one instance.

Example

Example.cppcpp
struct A { A(); };
struct B : A {
    std::string m;
    B() : A(), m("x") {} // A first, then m, then body
};

💡 Declaration order — not initializer-list order — governs members; base-specifier order governs bases.

What is multiple inheritance and when is it reasonable?

Answer

Multiple inheritance derives from more than one base. It is reasonable for mixin-style capabilities (e.g. a class that is both Serializable and Printable) but risky for stateful bases with overlapping members — ambiguity must then be qualified explicitly.

Prefer single inheritance plus interfaces/mixins, and use virtual inheritance only to solve a genuine diamond.

Example

Example.cppcpp
struct Printable { virtual void print() const = 0; };
struct Serializable { virtual std::string save() const = 0; };
struct Doc : Printable, Serializable {
    void print() const override {}
    std::string save() const override { return {}; }
};

💡 Say mixins yes, stateful multi-parent hierarchies no — that is the balanced interview answer.

What is the diamond problem and how does virtual inheritance fix it?

Answer

The diamond (D inherits B and C, both inherit A) gives D two A subobjects without virtual inheritance — ambiguous access and duplicated state. Declaring the B/C-to-A inheritance virtual makes all paths share a single A subobject, constructed by the most-derived class.

The cost is extra indirection and construction complexity, so virtual bases should stay small and stateless where possible.

Example

Example.cppcpp
struct A { int x = 0; };
struct B : virtual A {};
struct C : virtual A {};
struct D : B, C {}; // one shared A::x, not two
D d; d.x = 1; // unambiguous

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits