Virtual base class in C++





prowessapps.in
  • C++ supports multiple inheritance.

  • In the given diagram, suppose class A contains a public variable name X.

  • As per the given scenario, X is inherited in both classes i.e. class B and class C.

  • Here class D performed multiple inheritance. class D inherits class B and class C, so class D receives two copies of X variable of class A.

  • To overcome from this ambiguous situation due to multiple inheritance, C++ provides the keyword virtual.

  • For the given situation, you need to make class A as virtual base class.

  • If a base class inherited in derived class using virtual keyword, such base class is called VIRTUAL BASE CLASS.

  • Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple inheritance.

  • Each nonvirtual object contains a copy of the data members defined in the base class. This duplication wastes space and requires you to specify which copy of the base class members you want whenever you access them.

  • When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members. A single copy of its data members is shared by all the base classes that use it as a virtual base.

Example:
#include<iostream>
using namespace std;
class A{
public :
int x;
};
class B : virtual public A {
public :
int y;
}
class C : virtual public A {
public :
int z;
}
class D : public B, public C{
//some code here
}
//In the above code : class D will 
//get y, z and one copy of x                        
                    

Next topic is Abstract class





 




Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved