DEFINITION 13: MULTIPLE INHERITANCE - PRATMG/2143-OOP-Tamang GitHub Wiki

Multiple Inheritance is a C++ feature that allows a class to inherit from multiple classes. (one sub class is inherited from more than one base classes.) Inherited class constructors are called in the same order in which they are inherited.

multiple-inheritance

// C++ program to explain
// multiple inheritance
#include <iostream>
using namespace std;

// first base class
class Vehicle {
public:
	Vehicle()
	{
	cout << "This is a Vehicle" << endl;
	}
};

// second base class
class FourWheeler {
public:
	FourWheeler()
	{
	cout << "This is a 4 wheeler Vehicle" << endl;
	}
};

// sub class derived from two base classes
class Car: public Vehicle, public FourWheeler {

};

// main function
int main()
{
	// creating object of sub class will
	// invoke the constructor of base classes
	Car obj;
	return 0;
}

The Diamond Problem:

When two superclasses of a class share a base class, the diamond problem occurs. In the diagram below, for example, the TA class receives two copies of all attributes of the Person class, resulting in ambiguity.

diamondproblem

#include<iostream>
using namespace std;
class Person {
// Data members of person
public:
	Person(int x) { cout << "Person::Person(int ) called" << endl; }
};

class Faculty : public Person {
// data members of Faculty
public:
	Faculty(int x):Person(x) {
	cout<<"Faculty::Faculty(int ) called"<< endl;
	}
};

class Student : public Person {
// data members of Student
public:
	Student(int x):Person(x) {
		cout<<"Student::Student(int ) called"<< endl;
	}
};

class TA : public Faculty, public Student {
public:
	TA(int x):Student(x), Faculty(x) {
		cout<<"TA::TA(int ) called"<< endl;
	}
};

int main() {
	TA ta1(30);
}

The constructor of 'Person' is called twice in the above program. When the object 'ta1' is destroyed, the destructor of 'Person' will be called twice. As a result, object 'ta1' has two copies of all members of 'Person,' resulting in ambiguities. The 'virtual' keyword is the solution to this problem. We use 'Faculty' and 'Student' as virtual base classes to avoid having two copies of 'Person' in the 'TA' class. 

#include<iostream>
using namespace std;
class Person {
public:
	Person(int x) { cout << "Person::Person(int ) called" << endl; }
	Person()	 { cout << "Person::Person() called" << endl; }
};

class Faculty : virtual public Person {
public:
	Faculty(int x):Person(x) {
	cout<<"Faculty::Faculty(int ) called"<< endl;
	}
};

class Student : virtual public Person {
public:
	Student(int x):Person(x) {
		cout<<"Student::Student(int ) called"<< endl;
	}
};

class TA : public Faculty, public Student {
public:
	TA(int x):Student(x), Faculty(x), Person(x) {
		cout<<"TA::TA(int ) called"<< endl;
	}
};

int main() {
	TA ta1(30);
}

Reference:

⚠️ **GitHub.com Fallback** ⚠️