C++
Module 15: InheritanceIntermediate50 min read

Inheritance Types, Constructor Order & The Diamond Problem

Learn single, multiple, multilevel, and hierarchical inheritance, public/protected/private modes, constructor/destructor order, and virtual inheritance.

Key Takeaways & Core Concepts
  • `public` inheritance ("is-a"): Public stays public; protected stays protected.
  • `protected` / `private` inheritance: Models "implemented-in-terms-of" (composition is usually cleaner!).
  • Construction: Base -> Member objects -> Derived.
  • Destruction: Exact reverse (Derived -> Member objects -> Base).

1. Inheritance Types & Visibility Modes

C++ supports Single, Multilevel, Multiple, Hierarchical, and Hybrid inheritance.

  • `public` inheritance ("is-a"): Public stays public; protected stays protected.
  • `protected` / `private` inheritance: Models "implemented-in-terms-of" (composition is usually cleaner!).
1. Base Constructor Forwarding & Virtual Inheritance
1#include <iostream>
2#include <string>
3
4class Base {
5public:
6 Base(const std::string& msg) { std::cout << "Base: " << msg << "\n"; }
7 virtual ~Base() = default;
8};
9
10class Derived : public Base {
11public:
12 Derived() : Base("Initialized from Derived") { std::cout << "Derived ready\n"; }
13};
14
15int main() {
16 Derived d;
17 return 0;
18}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
18 lines
Note: Derived forwards arguments to the Base constructor via its initializer list.

2. Constructor & Destructor Execution Order

  • Construction: Base -> Member objects -> Derived.
  • Destruction: Exact reverse (Derived -> Member objects -> Base).

3. Diamond Problem & Virtual Inheritance

When D inherits from both B and C, and both inherit from A, D receives two A subobjects. Prefixing virtual public A on B and C shares a single A subobject.

Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)