In this blog post we will discuss virtual base class in c++ with example program. As we know every good concept is produced to solve a specific kind of problem. so we will discuss a problematic situation in c++ first and then we will grasp the concept of virtual base class in c++.

virtual base class in c++ with example program

Description of above diagram ( diamond problem)

  • Class A is parent class with data a.
  • The two classes , Class B and Class C are derived class , derived from parent Class A.
  • Class D is also a derived class , derived from Class B and Class C.
  • The class B and class C are derived from class A, in this case each of the class (B and C) will inherit a copy of base class A.
  • Since class D is derived from both of class B and class C , in this situation the class D will have a problem. Let see below simple example , will it compile?

The program will error out as,

Error explanation

The compiler will error out because , the derived class D when refers to the data in base class , it will get confused about the two copies of base data a.  This ambiguous situation in c++ inheritance is known as diamond problem.

virtual base class in c++ with example program

Using virtual keyword in the base class B and class C, we can resolve diamond problem. virtual inheritance force the two base classes B and C to share single copy of base class A.

 

Ref:

https://en.wikipedia.org/wiki/Virtual_inheritance




Related Contents to follow