What is a virtual base class? - C+++

What is a virtual base class?

- An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have duplicate sets of members inherited from a single base class.
- C++ solves this issue by introducing a virtual base class. When a class is made virtual, necessary care is taken so that the duplication is avoided regardless of the number of paths that exist to the child class.

What is Virtual base class? Explain its uses.

- When two or more objects are derived from a common base class, we can prevent multiple copies of the base class being present in an object derived from those objects by declaring the base class as virtual when it is being inherited. Such a base class is known as virtual base class. This can be achieved by preceding the base class’ name with the word virtual.
- Consider the following example :
class A
{
   public:
       int i;
};

class B : virtual public A
{
   public:
       int j;
};

class C: virtual public A
{
   public:
       int k;
};

class D: public B, public C
{
   public:
       int sum;
};

int main()
{
   D ob;
   ob.i = 10; //unambiguous since only one copy of i is inherited.
   ob.j = 20;
   ob.k = 30;
   ob.sum = ob.i + ob.j + ob.k;
   cout << “Value of i is : ”<< ob.i<<”\n”;
   cout << “Value of j is : ”<< ob.j<<”\n”; cout << “Value of k is :”<< ob.k<<”\n”;
   cout << “Sum is : ”<< ob.sum <<”\n”;

   return 0;
}
Explain the use of Vtable.
Explain the use of Vtable - Vtables are used for virtual functions. Its a shortform for Virtual Function Table....
Explain the problem with overriding functions
Explain the problem with overriding functions - Overriding of functions occurs in Inheritance. A derived class may override a base class member function.....
Overloading vs. overriding
Overloading vs. overriding - Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance. ....
Post your comment
Discussion Board
Wt happens inside when we use the keyword virtual
Please can you explain how and what happens and how it solves inside when we use virtual keyword
Hitesh 04-20-2017
internal working
please tell me about the internal working of the virtual base class.
mayank goyal 12-5-2016
definition
I need definition of Virtual Base Class in one line..
Sazzad 10-23-2016
virtual base
virtual base class avoid duplication .................
sahim reza 07-28-2016
Virtual keyword
The meaning of the keyword "virtual" is not correct in c++ compiler. It's vary confusing..
Uttam 05-7-2016
Where is the ambiguity ?
This is not correct example to show the use of Virtual Base Class ? In this program there is no ambiguity at all. It will work even without virtual keyword. Please update the program.
Shridhar 02-4-2016
java
can't understand easily....
krishna patil 08-11-2015
virtual base class
But the code would work fine, even without the virtual keyword!!
siddharth 12-3-2014