23 Nov 2019

  • November 23, 2019
  • Amitraj
Virtual base class in C++

-> 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.

-> The virtual base class is used when a derived class has multiple copies of the base class.


// C++ program on multipath inheritance using virtual base class.

#include<iostream>
using namespace std;
class A
{
public:
void showA()
{
cout<<"showA"<<" ";
}
};
class B: public virtual A
{
public:
void showB()
{
cout<<"showB"<<" ";
}
};

class C: public virtual A
{
public:
void showC()
{
cout<<"showC"<<" ";
}
};

class D: public B, public C
{
public:
void showD()
{
cout<<"showD";
}
};
int main()
{
D d;
d.showA();
d.showB();
d.showC();
d.showD();
return 0;
}

OUTPUT:

showA  showB  showC  showD


Translate

Popular Posts