#Previous question #Index of C++ Questions #Next question

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;
}

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

 Vote 0

Similar topics related to this section

object-oriented, C vs C++, C++ vs Java, encapsulation, constructor, overloaded constructor, destructor, destructor overloaded, copy constructor, copy constructor, deep copy, deep copy vs shallow copy, singleton, default access modifier, default access modifier, default access modifier, abstraction, THIS pointer, static function, THIS pointer, a static function, scope resolution operator, inline function, private vs protected, const function, polymorphism, operator overloading, function overloading, overriding, prefix vs postfix, friend class, friend function, sizeof class with virtual, vfptr and vftable, vfptr and vftable using C, early binding and late binding, inheritance, virtual function call from a constructor/destructor, virtual destructor, virtual base class, virtual base class, exception, stack unwinding, exception handling, try-catch block, namespace, mutable variable and const function, mutable keyword, explicit, access a member function, object slicing, ctor sequence of constructor, dtor sequence of destructor, virtual destructor, print the type, dynamic casting, static casting, dynamic and static casting, const casting, reinterpret casting, static and reinterpret casting, template class, template vs macro,

#Object-Oriented Programming in C++ (4th Edition)
#Programming: Principles and Practice Using C++ (2nd Edition)
#The C++ Programming Language, 4th Edition
#Professional C++ Paperback by Nicholas A.Solter, Scott J.Kleper
#Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14