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?
#include<iostream>
using namespace std;

class A {
protected:
	int a; // data
};

class B: public A {
};
class C: public A {
};

class D: public B, public C {
public:
	void print()
	{
		cout << a;
	}
};

int main() {
	return 0;
}

The program will error out as,

../main.cpp: In member function ‘void D::print()’:
../main.cpp:18:11: error: reference to ‘a’ is ambiguous
   cout << a;
           ^
../main.cpp:6:6: note: candidates are: int A::a
  int a; // data

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.

#include<iostream>
using namespace std;

class A {
protected:
	int a; // data
};

class B: virtual public A {
};
class C: virtual public A {
};

class D: public B, public C {
public:
	void print()
	{
		cout << a;
	}
};

int main() {
	return 0;
}

 

Ref:

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



Related Contents to follow