TalentJR

🧩 C++ programming tutorial for beginners · Class 11 · Lesson 15 of 18 · Free

Multiple Inheritance in C++ – Two Parents, Ambiguity and the Diamond Problem

⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in

In this lesson you will

  • Create a class that inherits from two parent classes
  • Predict constructor and destructor order and fix name clashes
  • Explain the diamond problem and solve it with virtual inheritance

Kavya is a student AND the school cricket captain. She has a roll number and marks, and she also has runs and a team. In Lesson 3 a class had one parent. C++ also lets a class have two or more parents, which is powerful but needs care.

What is multiple inheritance in C++?

Multiple inheritance means a class has more than one parent. List the parents after the colon, separated by commas, each with its own public.

The child gets the members of every parent. A SportsStudent can call study() from Student and play() from Player.

A SportsStudent can also be used wherever a Student or a Player is expected. Try it: add a function void printMarks(const Student& s) and pass k to it.

🧩 C++ — you can edit this code
Output
Studying, marks now 85
Batting, runs now 30
Kavya: 85 marks, 30 runs

In what order are constructors called with multiple inheritance in C++?

Parents are built first, in the order they are LISTED after the colon. The order you write in the initializer list does not change this.

Then the child's own constructor body runs. Destructors run in exactly the reverse order (Lesson 7).

Try it: swap the order to public Battery, public Camera and run again.

🧩 C++ — you can edit this code
Output
Camera on
Battery on
Phone ready
--- using the phone ---
Phone shutting down
Battery off
Camera off

What if two parent classes have a function with the same name in C++?

If both parents have show(), then k.show() is ambiguous: the compiler cannot guess which one you mean, so it refuses to compile.

Fix 1: name the parent with the scope operator, k.Student::show(). Fix 2 (usually better): write show() in the child class and decide there what it does.

Here the child's show() calls both parents' versions, so the report has everything in one place.

🧩 C++ — you can edit this code
Output
Kavya's report
Marks: 86
Runs: 412
Runs: 412

What is the diamond problem in C++?

Suppose Student and Employee both inherit from Person, and Intern inherits from both. Drawn on paper, the four classes make a diamond shape.

By default an Intern then contains TWO separate Person parts: one through Student and one through Employee. The Person constructor runs twice, and there are two different names.

Writing i.name is ambiguous. You can see the two copies below: each one is reached through a different parent.

🧩 C++ — you can edit this code
Output
Person built
Person built
As student: Rahul
As employee: R. Kumar

How does virtual inheritance solve the diamond problem in C++?

Write virtual public Person in BOTH middle classes. Now every Intern shares ONE Person part, and i.name is no longer ambiguous.

With virtual inheritance, the most-derived class (Intern) builds the shared Person itself, before anything else. That is why Intern's initializer list calls Person(n) directly.

Many teams avoid diamonds altogether. A common safe style: inherit data from at most one class, and add abilities through interfaces (Lesson 13) that have no data.

🧩 C++ — you can edit this code
Output
Person built: Rahul
Name: Rahul
Name: Rahul Kumar

🤔 Predict the output

Think like C++: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

#include <iostream>
using namespace std;

class A { public: A() { cout << "A"; } };
class B { public: B() { cout << "B"; } };
class C : public B, public A {
public:
    C() : A(), B() { cout << "C"; }
};

int main() {
    C c;
    cout << "\n";
    return 0;
}

Question 2. In what order do the destructors run?

#include <iostream>
using namespace std;

class A { public: ~A() { cout << "a"; } };
class B { public: ~B() { cout << "b"; } };
class C : public A, public B { public: ~C() { cout << "c"; } };

int main() {
    {
        C obj;
    }
    cout << "\n";
    return 0;
}

Question 3. How many times is a Person built?

#include <iostream>
using namespace std;

int built = 0;
class Person { public: Person() { built++; } };
class Student : virtual public Person {};
class Employee : virtual public Person {};
class Intern : public Student, public Employee {};

int main() {
    Intern a;
    Intern b;
    cout << built << "\n";
    return 0;
}

🧩 Your challenge

Make a LibraryCard that is both Printable and Chargeable. Printable is an interface with print(). Chargeable is an interface with lateFee(int days) and has no data. LibraryCard has a student name and charges Rs 2 per late day, but never more than Rs 50. Write a function that takes const Printable& and another that takes const Chargeable&, and pass the same card to both. Expected output: Card: Ananya Fee for 4 days: Rs 8 Fee for 40 days: Rs 50

Expected output :
Card: Ananya
Fee for 4 days: Rs 8
Fee for 40 days: Rs 50
🧩 C++ — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

#include <iostream>
using namespace std;

class Student { public: void show() const { cout << "Marks: 86\n"; } };
class Player  { public: void show() const { cout << "Runs: 412\n"; } };
class SportsStudent : public Student, public Player {};

int main() {
    SportsStudent k;
    k.show();
    return 0;
}

Line 10: error: member 'show' found in multiple base classes of different types

✅ Right

#include <iostream>
using namespace std;

class Student { public: void show() const { cout << "Marks: 86\n"; } };
class Player  { public: void show() const { cout << "Runs: 412\n"; } };
class SportsStudent : public Student, public Player {};

int main() {
    SportsStudent k;
    k.Student::show();
    return 0;
}

Both parents have show(), so k.show() is ambiguous. Say which parent you mean, or write show() in the child class.

❌ Wrong

#include <iostream>
#include <string>
using namespace std;

class Person { public: string name = "Rahul"; };
class Student : public Person {};
class Employee : public Person {};
class Intern : public Student, public Employee {};

int main() {
    Intern i;
    cout << i.name << "\n";
    return 0;
}

Line 12: error: non-static member 'name' found in multiple base-class subobjects of type 'Person':

✅ Right

#include <iostream>
#include <string>
using namespace std;

class Person { public: string name = "Rahul"; };
class Student : virtual public Person {};
class Employee : virtual public Person {};
class Intern : public Student, public Employee {};

int main() {
    Intern i;
    cout << i.name << "\n";
    return 0;
}

Without virtual inheritance an Intern has two Person parts, so i.name is ambiguous. Use virtual public Person in both middle classes.

❌ Wrong

#include <iostream>
using namespace std;

class Student { public: void study() const { cout << "Studying\n"; } };
class Player  { public: void play() const { cout << "Playing\n"; } };
class SportsStudent : public Student, Player {};

int main() {
    SportsStudent k;
    k.study();
    k.play();
    return 0;
}

Line 11: error: 'play' is a private member of 'Player'

✅ Right

#include <iostream>
using namespace std;

class Student { public: void study() const { cout << "Studying\n"; } };
class Player  { public: void play() const { cout << "Playing\n"; } };
class SportsStudent : public Student, public Player {};

int main() {
    SportsStudent k;
    k.study();
    k.play();
    return 0;
}

public applies to one parent only. Player without it is inherited privately (the default for class), so play() cannot be called from outside. Write public before each parent.

📌 Remember

  • A class can have several parents: class C : public A, public B.
  • Parents are built in the order listed after the colon; destructors run in reverse.
  • Same function name in two parents is ambiguous: use A::f() or override it in the child.
  • The diamond problem: two copies of the shared grandparent.
  • virtual public Base in the middle classes gives one shared copy, built by the most-derived class.
  • Safest style: one data parent plus interfaces with no data.

Finished the quiz and the challenge?

Questions students ask

Does Java or Python have multiple inheritance like C++?

Python allows multiple inheritance of classes. Java does not allow two parent classes, but a class can implement many interfaces. C++ allows both, so you choose how careful to be.

What is the diamond problem in C++?

It happens when a class inherits from two classes that share the same parent. The bottom class gets two copies of the top class, so names become ambiguous. Virtual inheritance makes the copies into one.

Is multiple inheritance bad in C++?

Not bad, but easy to misuse. Inheriting from several interfaces is common and safe. Inheriting data from several classes, especially in a diamond, makes code harder to understand.

What does virtual inheritance cost?

The object needs a little extra hidden information to find its shared base, and the most-derived class must build that base. For small programs the cost does not matter.