EduC++ / Inheritance in C++

Inheritance in C++

Prereqs Classes, access specifiers, constructors, virtual functions
Standard C++20 (uses std::format)

Frequently Asked Questions

QWhat is the difference between virtual and non-virtual member functions?
AA non-virtual function is resolved at compile time based on the static type of the pointer or reference. A virtual function is resolved at runtime via the vtable, so calling through a base pointer dispatches to the correct derived override. Declare a function virtual when you expect derived classes to override it and you call through base pointers or references.
QWhen should I use multiple inheritance?
AUse multiple inheritance when a class genuinely models two or more independent capabilities (e.g., Flyable and Swimmable). Avoid it for sharing implementation from unrelated hierarchies — prefer composition in that case. If two bases share a common ancestor, use virtual inheritance to avoid the diamond problem.
QHow does virtual inheritance solve the diamond problem?
AWithout virtual inheritance, a class that inherits from two bases sharing a common grandparent gets two copies of the grandparent sub-object, causing ambiguity. Virtual inheritance ensures only one shared instance of the common base exists. The most-derived class is responsible for constructing the virtual base, regardless of inheritance depth.
QWhat does the final keyword do in C++?
AApplied to a class, final prevents any further derivation from it. Applied to a virtual function, final prevents derived classes from overriding that specific function. The compiler can also use final to devirtualize calls, turning virtual dispatch into direct calls when it can prove the concrete type, improving performance.
C++
#include <iostream>
#include <format>
#include <string>

1 Base class

What

A base class defines shared state and behavior that derived classes inherit and optionally override.

When

Use this when multiple types share common attributes and operations that can be factored into a single parent.

Why

It eliminates code duplication and establishes the interface through which derived objects can be used polymorphically.

Use

Give the base class a virtual destructor, define virtual methods for overridable behavior, and use protected for derived-accessible members.

C++ Version C++98+ (virtual destructor, override keyword C++11)

Represents a generic animal with common attributes.

polymorphism, its destructor MUST be virtual. Without it, deleting a derived object through a base pointer is undefined behaviour -- the derived destructor never runs, leaking any resources it owns.

Watch out: If a class will ever be used as a base for

C++
class Animal {
protected:                      // Accessible to derived classes
    std::string name_;
    int age_;

public:
    Animal(std::string name, int age)
        : name_(std::move(name)), age_(age) {
        std::cout << std::format("  Animal '{}' constructed\n", name_);
    }

    virtual ~Animal() {
        std::cout << std::format("  Animal '{}' destroyed\n", name_);
    }

    void info() const {
        std::cout << std::format("Name: {}, Age: {}\n", name_, age_);
    }

    // Virtual method: can be overridden by derived classes
    virtual void speak() const {
        std::cout << std::format("{} makes a sound\n", name_);
    }
};
Inheritance Memory Layout Deep Dive
 

Watch out: Always mark overriding methods with the override keyword. Without it, a small typo in the function signature (wrong parameter type, missing const) silently creates a NEW function instead of overriding the base version. The override keyword turns that silent bug into a compile-time error.

override Checking Deep Dive
When the compiler sees the override keyword on a method, it
   verifies that a virtual function with the EXACT same signature
   (name, parameter types, const/volatile qualifiers, ref-qualifiers)
   exists in a base class.  If no matching base virtual function is
   found, compilation fails immediately.

   Without override, a mismatched signature silently creates a brand-
   new virtual function in the derived class that hides the base
   version.  For example:
       // Base:    virtual void speak() const;
       // Derived: void speak();          // missing const — NEW function!
   The derived speak() does NOT override the base speak() const; it
   hides it.  Calls through a Base* still invoke Base::speak() const.
   Adding override catches this at compile time:
       void speak() override;   // ERROR: does not override any base method

   Reference: reference/en/cpp/language/override
C++
class Dog : public Animal {
    std::string breed_;

public:
    // Call the base class constructor explicitly
    Dog(std::string name, int age, std::string breed)
        : Animal(std::move(name), age), breed_(std::move(breed)) {}

    // Override the base class virtual method
    void speak() const override {
        std::cout << std::format("{} barks! (breed: {})\n", name_, breed_);
    }

    void fetch() const {
        std::cout << std::format("{} fetches the ball!\n", name_);
    }
};

class Cat : public Animal {
public:
    Cat(std::string name, int age)
        : Animal(std::move(name), age) {}

    void speak() const override {
        std::cout << std::format("{} meows!\n", name_);
    }
};

3 Multilevel inheritance

What

Multilevel inheritance.

When

Use this when it cleanly solves the problem in front of you.

Why

GuideDog -> Dog -> Animal.

Use

Use it in code like: class GuideDog : public Dog {.

C++ Version Not explicitly specified in this example.

GuideDog -> Dog -> Animal

C++
class GuideDog : public Dog {
    std::string owner_;

public:
    GuideDog(std::string name, int age, std::string breed, std::string owner)
        : Dog(std::move(name), age, std::move(breed)), owner_(std::move(owner)) {}

    void guide() const {
        std::cout << std::format("{} guides {}\n", name_, owner_);
    }
};

4 Multiple inheritance

What

Multiple inheritance.

When

Use this when it cleanly solves the problem in front of you.

Why

Combine capabilities from two unrelated bases.

Use

Use it in code like: class Flyable {.

C++ Version Not explicitly specified in this example.

Combine capabilities from two unrelated bases.

get the "diamond problem" -- the derived class holds TWO copies of the shared base, causing ambiguity. Solve it with virtual inheritance (class B : virtual public A) so only one shared base sub-object exists. Be aware that virtual inheritance adds a small runtime cost (extra indirection through a vptr) and complicates constructor ordering.

Watch out: When two base classes share a common ancestor you

The Diamond Problem Deep Dive
Without virtual inheritance, each inheritance path creates its
   own copy of the shared base:

       class A { int x_; };
       class B : public A {};
       class C : public A {};
       class D : public B, public C {};

       D object layout (no virtual inheritance):
       +---------------------+
       | B sub-object:       |
       |   A sub-object (#1) |  <- first copy of A
       |     x_              |
       |   [B members]       |
       +---------------------+
       | C sub-object:       |
       |   A sub-object (#2) |  <- second copy of A
       |     x_              |
       |   [C members]       |
       +---------------------+

   Accessing d.x_ is ambiguous — the compiler does not know which
   copy you mean (B::x_ or C::x_), and you get a compile error.

   With virtual inheritance the compiler shares a single A:

       class B : virtual public A {};
       class C : virtual public A {};
       class D : public B, public C {};

       D object layout (virtual inheritance):
       +---------------------+
       | B sub-object:       |
       |   vbase_ptr --------+--> offset to shared A
       |   [B members]       |
       +---------------------+
       | C sub-object:       |
       |   vbase_ptr --------+--> offset to shared A
       |   [C members]       |
       +---------------------+
       | A sub-object (shared)|  <- single copy of A
       |   x_                 |
       +----------------------+

   Each intermediate class (B, C) holds a hidden vbase pointer that
   the compiler uses to locate the single shared A sub-object at
   runtime.  Because A's position relative to B or C can vary, the
   most-derived class (D) is responsible for constructing the virtual
   base — D's member initializer list must call A's constructor
   directly, regardless of the inheritance depth.

   Reference: reference/en/cpp/language/derived_class
C++
class Flyable {
public:
    virtual void fly() const {
        std::cout << "Flying!\n";
    }
    virtual ~Flyable() = default;
};

class Swimmable {
public:
    virtual void swim() const {
        std::cout << "Swimming!\n";
    }
    virtual ~Swimmable() = default;
};

// A duck can fly AND swim
class Duck : public Animal, public Flyable, public Swimmable {
public:
    Duck(std::string name, int age)
        : Animal(std::move(name), age) {}

    void speak() const override {
        std::cout << std::format("{} quacks!\n", name_);
    }
};

5 Protected inheritance and 'using' keyword

What

Protected inheritance and 'using' keyword.

When

Use this when it cleanly solves the problem in front of you.

Why

It improves correctness, clarity, and maintainability.

Use

Use it in code like: class Base {.

C++ Version Not explicitly specified in this example.
C++
class Base {
public:
    void public_method() const {
        std::cout << "Base::public_method\n";
    }

protected:
    void protected_method() const {
        std::cout << "Base::protected_method\n";
    }
};

class Derived : protected Base {
public:
    // Re-expose selected base methods with 'using'
    using Base::public_method;

    void call_protected() const {
        protected_method();  // Accessible because we inherit protected
    }
};

C++
int main() {
    std::cout << "--- Single Inheritance ---\n";
    Dog rex("Rex", 5, "German Shepherd");
    rex.info();      // Inherited from Animal
    rex.speak();     // Overridden in Dog
    rex.fetch();     // Dog-specific

    std::cout << "\n--- Multilevel Inheritance ---\n";
    GuideDog buddy("Buddy", 3, "Labrador", "Alice");
    buddy.info();
    buddy.speak();
    buddy.guide();

    std::cout << "\n--- Multiple Inheritance ---\n";
    Duck donald("Donald", 2);
    donald.speak();
    donald.fly();
    donald.swim();

    std::cout << "\n--- Protected Inheritance ---\n";
    Derived d;
    d.public_method();    // OK: re-exposed with 'using'
    d.call_protected();   // OK: calls protected method internally
    // d.protected_method(); // Error: not accessible from outside

    std::cout << "\n--- Destruction order (reverse of construction) ---\n";
    return 0;
}