What is Virtual base class? Explain its uses.
Page 1 of 1
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 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;
}.
Similar topics
» Describe abstract base class. Illustrate an example to explain it.
» When does a class need a virtual destructor?
» What is virtual function? Explain with an example
» What is a virtual destructor? Explain the use of it.
» Explain container class.
» When does a class need a virtual destructor?
» What is virtual function? Explain with an example
» What is a virtual destructor? Explain the use of it.
» Explain container class.
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum