Diamond Problem in C+

Problem: 

Diamond problem is the scenario in hybrid or multiple inheritance, when a derived class inherit the 2 or more classes which inherit the same base class. In this case, Derived Class 3 acquires the 2 copies of the Base Class which is inherited by the Derived Class 1 & Derived Class 2. So an ambiguous situation appear while accessing the members of the Base class by Derived Class 3.


Diamond Problem in Inheritance


Solution :
The ambiguity in the above mentioned problem will be removed by making the Base Class virtual by using the virtual keyword while Derived Class 1 & Derived Class 2 inherit the Base Class.
It will pass a single copy to the Derived Class 3, when Derived Class 3 inherit the Derived Class 1 & Derived Class 2.


// This code will explain the diamond problem by using Animal Class as Base Class.
// Bird - Derived Class 1, Mammal - Derived Class 2, Bat - Derived Class 3


#include<iostream>

using namespace std;

class Animal
{
public:
Animal()
{
cout << "\nAnimal makes sound : Animal class" << endl;
}
};

class Mammal : virtual public Animal
{
public:
Mammal()
{
cout << "Mammal makes sound : Mammal class" << endl;
}

};

class Bird : virtual public Animal
{
public:
Bird()
{
cout << "Bird makes sound : Bird class" << endl;
}

};

class Bat : public Mammal, public Bird
{
public:
Bat()
{
cout << "Bat makes sound : Bat class" << endl;
}
};


int main()
{
Bat bat;

return 0;
}

Comments

Popular posts from this blog

Setting up a USB thermal printer with a Raspberry Pi 3B+

Autostart an app on reboot - Raspberry Pi

Basic Input/Output C Program