What is the need for Virtual base classes?
- Required in scenarios of multiple inheritance where the derivation is like diamond.
- Compiler reports an error since there is a ambiguity since the derived class (Derived3) sees 2 instance of base class (Base).
- Using the keyword virtual in the derived classes (Derived1, Derived2) resolves this ambiguity by allowing them to share a single instance of base class.

EXAMPLE: Demonstrate the compilation error in the Diamond problem
#include <iostream>
using namespace std;
class Base {
protected:
int iData;
public:
Base() {
iData = 10;
}
};
class Derived1 : public Base {
};
class Derived2 : public Base {
};
class Derived3 : public Derived1, public Derived2 {
public:
int GetData() {
return iData;
}
};
void main ()
{
Derived3 obj;
cout << obj.GetData() << endl;
}
OUTPUT:
Error E2014 Diamond.cpp 24: Member is ambiguous: 'Base::iData' and 'Base::iData in function Derived3::GetData()
*** 1 errors in Compile ***
EXAMPLE: Demonstrate the usage of virtual base class in the Diamond problem to fix the compilation error#include <iostream>
using namespace std;
class Base {
protected:
int iData;
public:
Base() {
iData = 10;
}
};
class Derived1 : virtual public Base {
};
class Derived2 : virtual public Base {
};
class Derived3 : public Derived1, public Derived2 {
public:
int GetData() {
return iData;
}
};
void main ()
{
Derived3 obj;
cout << obj.GetData() << endl;
}
OUTPUT:
10
Simple and clear explanation. Thanks for the code sample.
ReplyDelete