Skip to content
AgileLogics
4 min read

Multiple Inheritance

Prerequisites: File I/O with streams

Unlike Java (single inheritance, plus interfaces), a C++ class can inherit from more than one base class directly:

class Flyable {
public:
    virtual void fly() = 0;
    virtual ~Flyable() = default;
};

class Swimmable {
public:
    virtual void swim() = 0;
    virtual ~Swimmable() = default;
};

class Duck : public Flyable, public Swimmable {
public:
    void fly() override { std::cout << "Flying" << std::endl; }
    void swim() override { std::cout << "Swimming" << std::endl; }
};

This is genuinely powerful but introduces the diamond problem when two base classes share a common ancestor — solved with virtual inheritance on that shared base, a niche-enough case that most real code sidesteps it by preferring composition, or single inheritance plus pure-abstract "interface" classes like Flyable above.

Common mistakes

  • Reaching for multiple inheritance to share implementation across two base classes — this is where the diamond problem and genuine design confusion creep in. Multiple inheritance is safest when every base beyond the first is a pure abstract interface.