Virtual base class in C++





Virtual base class in C++

Consider the situation, with a base class, parent; two derived classes, child1 and child2; and a fourth class, grandchild, derived from both child1 and child2.

E.g.

 

#include<iostream.h>

#include<stdio.h>

Class parent

{

Public:

Int a;

};

Class child1: public parent

{

Public:

Int b;

};

Class child2: public parent

Int c;

};

Class grandchild: public child1, public child2

{

Public:

Int total;

};

Void main ()

{

Grandchild obj;

Obj.y=25;

Obj.y=50;

Obj. Total=obj.a+obj.b+obj.c;

Cout<<”\n total=”<<obj. Total;

getch ();

}

As child1 and child2 inherit parent, they both have copies of parents. However, grandchild inherits both child1 and child2. This means that there are two copies of parents in an object of type grandchild. Therefore in the expression

Obj.y=25;

Which A is being referred the one in child1 or the one in child2. The situation is ambiguous. To estimate this ambiguity, we make child1 and child2 into virtual base class as below:-

Class parent

{

——————————-

———————————–

};

Class child1: virtual public parent            //shares copy of parent

{

————————-

————————–

};

Child child2: virtual public parent               //shares copy of parent

{

————————-

—————————–

};

Class grandchild: public child1, public child2

{

———————————–

———————————-

};

The use of keyword virtual in these two classes causes them to share a single copy of their base class parent.

Now, since there is only one copy of parent, there is no ambiguity when it is referred to in grandchild. Hence, the virtual base class restricts its derived class from having the multiple copies of common ancestor.



Related posts:

  1. C++ Base Class Type of base classes in C++ A base class can...
  2. Array of class objects Array of class objects and single inheritance A program consisting...
  3. Overriding Member Function in C++ Overriding member function We can define data member and member...
  4. Class Hierarchies Class Hierarchies The relationship between a base ad derived classes...
  5. Array Of Class Object Array of class objects Array is a collection of similar...