In c++ you would have heard about famous Dreaded Diamond problem, where a class appears more than once in the inheritance hierarchy.
for eg:
Here there is ambiguity as A is inherited twice so there are two copies of A::data in the object of D d.This Piece of code can be corrected if
But this is not the full solution we require, instead we use virtual inheritance. where class B and C virtually inherit class A. so that only one copy of class A member data is found in D d object.
A powerful technique for customizing the behavior of polymorphic classes called cross delegation or Delegate to a sister class.
for eg:
Here class A becomes a abstract class as the methods function1() and function2() are pure virtual functions.Which means in the Vtable of this class, these functions addresses are set to Null.
When Class B and C inherits class A and does not contain the definitions of both functions they too become abstract. so when class D inherits it both B and C (where class B & C should have been inherited class A virtually) the Vtable of class D contains:
&B::function1()
&C::function2()
so when we create object of D d it gets created without any problem and definitions of the functions are picked from both classes.
for eg:
Code:
#include <iostream>
using namespace std;
class A
{
public:
int data;
};
class B : public A
{
};
class C : public A
{
};
class D: public B, public C
{
public :
void function(void)
{
data = 1;
}
};
int main (void)
{
D d;
d.function();
return 0;
}
Code:
void function(void)
{
B::data = 1; or C::data = 1;
}
Code:
class B : virtual public A
{
};
class C : virtual public A
{
};
for eg:
Code:
#include <iostream>
using namespace std;
class A
{
public:
virtual void function1(void) = 0;
virtual void function2(void) = 0;
};
class B : virtual public A
{
public:
void function1(void)
{
cout<<"FUNCTION ONE"<<endl;
}
};
class C : virtual public A
{
public:
void function2(void)
{
cout<<"FUNCTION TWO"<<endl;
}
};
class D : public B, public C
{
};
int main (void)
{
D d;
d.function1();
d.function2();
return 0;
}
When Class B and C inherits class A and does not contain the definitions of both functions they too become abstract. so when class D inherits it both B and C (where class B & C should have been inherited class A virtually) the Vtable of class D contains:
&B::function1()
&C::function2()
so when we create object of D d it gets created without any problem and definitions of the functions are picked from both classes.
shabbir
like this




