We derive a class 'class3' from 'class1' and 'class2' which in turn have been derived from a base class 'base'. If a member function of 'class3' wants to access data or function in the base class, it hits a deadlock. Since 'class1' and 'class2' are both derived from 'base', each inherits a copy of 'base' and each copy, called sub-object, contains its own copy of 'base's data. Now when 'class3' refers to the data in the 'base' class, it is unclear to the compiler which copy to access and hence reports an error. To get rid of this situation, we make 'class1' and 'class2' as virtual base classes. Using keyword virtual in the two base classes causes them to share the same sub-object of the base class and then 'class1' and 'class2' are known as virtual base class.

Example: Program showing use of virtual base class.

#include<iostream.h>
class base
{
  protected: int data;
  public: base()
  {
    data = 500;
  }
};
class class1 : virtual public base
{
};
class class2 : virtual public base
{
};
class class3:public class1, public class2
{
  public: int getdata()
  {
    return data;
  }
};
int main (int argc, char *argv[])
{
  class3 c;
  int a;
  a = c.getdata();
  cout << a;
}

About our authors: Team EQA

You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.

#