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

Related Posts:

  • Benefits of OOP Benefits of OOP -> The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program.  -> It is possible to have multiple instances of object… Read More
  • // c++ program to check given no. is odd or even using class // c++  program to check given no. is odd or even using class    By Amit raj purohit http://codevidyalay.blogspot.com #include<iostream> using namespace  std; class number { private: … Read More
  • Calculate area using class ... // c++ program to calculate area using class              By Amit raj purohit http://codevidyalay.blogspot.com #include<iostream> using namespace std; class  shape { pr… Read More
  • C++ Features Cpp Features C++ is object oriented programming language. It provides a lot of features that are given below. 1. Mid-level programming language 2. Structured programming language 3. Rich Library 4. Simple 5. Machine Indep… Read More
  • Age using class   // cpp program to display age using class          By Amit purohit http://codevidyalay.blogspot.com #include<iostream> using namespace std; class person { char name[10]; int a… Read More

Translate

Popular Posts