Virtual Base Class
Virtual Base Class
AND
VIRTUAL FUNCTION
Need for Virtual Base Classes
• Consider the situation where we have one
class A .
• This class is A is inherited by two other
classes B and C.
• Both these class are inherited into another in
a new class D .
(as shown in figure)
class A are inherited twice to class D.
• data members/function of class A are
inherited twice to class D.
• One through class B and second through
class C.
• When any data / function member of class A is
accessed by an object of class D, ambiguity
arises
• which data/function member would be
called? One inherited through B or the other
inherited through C.
• This confuses compiler and it displays error.
Example
class A {
{ };
public:
void show() class D : public B, public C
{ {
cout << "Hello form A "; };
}
}; int main()
{
class B : public A D object;
{ object.show();
}; }
class C : public A
How to resolve this issue?
• To resolve this ambiguity when class A is
inherited in both class B and class C, it is
declared as virtual base class by placing a
keyword virtual as :
• Syntax for Virtual Base Classes:
• Syntax 1: class B : virtual public A { };
Syntax 2: class C : public virtual A { };
• virtual can be written before or after
the public.
• ((Derived*)ptr)->display();