Learn C++
#include "oopadvanced/multiple_inheritance.hpp"

Multiple Inheritance in C++

//concept

C++ allows inheriting from several bases at once (class Duck : public Bird, public Swimmer), mixing capabilities that single-chain inheritance can't express. Used sparingly for capability mixins and interface combinations, it is powerful and safe; used for tangled state hierarchies, it breeds the diamond problem.

The diamond — D inherits B and C, both inheriting A — duplicates A's members in D unless the inheritance is virtual (class B : virtual public A), which shares one A subobject. Most style guides permit multiple inheritance for interfaces (pure-abstract bases) and discourage it for stateful bases.

//how it works
1

Capability mixing

class Duck : public Bird, public Swimmer combines two independent behaviors — each base contributes its own interface and state.

2

The diamond problem

If B and C both derive from A, D(B,C) holds two A subobjects — d.member is ambiguous until qualified as d.B::member.

3

virtual inheritance shares

class B : virtual public A makes all paths share a single A subobject — the standard diamond fix, with slight construction-order rules.

4

Interfaces multiply safely

Multiple pure-abstract bases carry no state to duplicate — mixin interfaces freely, restrict stateful multiple inheritance.

//example
#include <iostream>
 
class Flyer {
public:
void fly() { std::cout << "flying" << std::endl; }
};
 
class Swimmer {
public:
void swim() { std::cout << "swimming" << std::endl; }
};
 
class Duck : public Flyer, public Swimmer {};
 
int main() {
Duck d;
d.fly();
d.swim();
return 0;
}
Output
flying
swimming
1Duck inherits both bases' interfaces with no ambiguity — fly and swim are distinct names.
2d.fly() resolves to Flyer's method, d.swim() to Swimmer's — one object, two capabilities.
3Both lines print, showing clean capability mixing when bases don't overlap.
//use cases
Mixin capabilities (Serializable + Printable + Observable) onto domain classes
Combining multiple pure interfaces in plugin and COM-style architectures
Resolving diamonds with virtual inheritance in legacy hierarchies
Preferring composition when the relationship is has-a rather than is-a

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.