Write short notes on virtual Base Class

Estudies4you

3.1.3. Virtual Base Class

Q16. Write short notes on virtual Base Class.
Answer:
C++ has introduced the keyword ‘virtual’ to avoid the ambiguity that takes place by multi-path inheritance. When the word virtual is used before the name of a class, it specifies that the class is virtual and indicates the compiler to take some essential caution in order to prohibit the duplication of member variables. A base class is always declared as virtual, because it is the class from which other classes are derived.
Thus, virtual base class is a class in which virtual keyword is placed before the name of base class while it is inherited. Example to illustrate the syntax for declaring Virtual Base classes,
class X
{
protected:
int x;
};
class Y : virtual public X //declaration of virtual classes
{
protected:
int y;
};
class Z : virtual public X //declaration of virtual class
{
protected:
int z;
};
class M : public Y,Z
{
int m;
};
Program
#include<iostream.h>
#include<conio.h>
class Base
{
protected:
int b;
};
class D1 : public virtual Base //declaration of virtual base‘class.
{
protected: :
int dl;  //declaration of member variable
};
class D2 : public virtual Base //declaration of virtual class
{
protected:
int d2;  //declaration of member variable
};
class D3 : public D1, D2 //declaration of virtual class
{
int d3; //declaration of member of variable
public:
void get() //declaration of member function D3.
{
cout<< “Give the input values for b,d1,d2 and d3 =”;
cin>>b>>d1>>d2>>d3;
}
void put( )
{
cout<<“b=”<<b;
cout<<“\nd1=” <<d1;
cout<<“\nd2=” <<d2;
cout<<“\nd3=” <<d3;
}
};
int main()
{
clrscr();
D3 x;
x.get(); //data is read
x.put(); //data is displayed
getch();
return 0;
}

Output
Virtual Base Class in c++,virtual keyword in c++,use of Virtual Base Classes in c++,examples of Virtual Base Class,program for Virtual Base Class in c++,estudies4you,c++ notes jntuh,c++ lecture notes jntuh,c++ study material jntuh,oops using c++ lecture notes jntu

To Top