In multiple inheritance, multiple classes are inherited i.e., when class needs properties of two or more classes and follows “Is-A” relationship as well.
Let us take an example to understand the concept of multiple inheritance.
#include <iostream>
using namespace std;
class waterHabitat
{
public:
waterHabitat() {
cout << “water Habitat c’tor” << endl;
}
~ waterHabitat() {
cout << “water Habitat d’tor” << endl;
}
};
class landHabitat
{
public:
landHabitat() {
cout << “land Habitat c’tor” << endl;
}
~ landHabitat() {
cout << “land Habitat d’tor” << endl;
}
};
class amphibian : public waterHabitat, public landHabitat {
public:
amphibian() {
cout << “amphibian c’tor” << endl;
}
~ amphibian() {
cout << “amphibian d’tor” << endl;
}
};
int main()
{
amphibian obj;
return 0;
}
Output:
water Habitat c’tor
land Habitat c’tor
amphibian c’tor
amphibian d’tor
land Habitat d’tor
water Habitat d’tor
- In the above example, amphibian is inherited from two base classes viz. waterHabitat and landHabitat since amphibian is-a water and land habitat and has properties of both.
- Order of construction is based on how the classes are inherited and not how they are initialised in the initializer list. Like in the above example, first waterHabitat is inherited then landHabitat. So, when the amphibian object is created, then order of constructer is waterHabitat, landHabitat and eventually amphibian.
- Order of destruction is reverse i.e., amphibian, landHabitat and waterHabitat.
- landHabitat and waterHabitat has default constructor. But if they have parameterized constructor, then it is the responsibility of amphibian(derived) class to initialize the base classes first i.e. landHabitat and waterHabitat in the initializer list of amphibian (Derived) class.