Virtual Base Class
Virtual Base Class
class C : public A {
};
Compile Errors:
• prog.cpp: In function 'int main()':
• prog.cpp:29:9: error: request for member 'show' is
ambiguous
• object.show();
^
• prog.cpp:8:8: note: candidates are: void A::show()
• void show()
^
• prog.cpp:8:8: note: void A::show()
How to resolve this issue?
• To resolve this ambiguity when class A is inherited in both class B and
class C, it is declared as virtual base class by placing a keyword virtual as :
• Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
Note:
• virtual can be written before or after the public.
• Now only one copy of data/function member will be copied
to class C and class B and class A becomes the virtual base
class.
• Virtual base classes offer a way to save space and avoid
ambiguities in class hierarchies that use multiple inheritances.
• 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 virtual base.
Example
#include <iostream>
using namespace std;
int main()
{
class A {
public: D object; // object creation of
int a; class d
A() // constructor
{ cout << "a = " << object.a << endl;
a = 10;
}
}; return 0;
class B : public virtual A { }
};
/* Other members */
};
A complete example:
• A pure virtual function is implemented by class Derived: public Base
classes which are derived from a Abstract {
class. Following is a simple example to int y;
demonstrate the same. public:
void fun() { cout << "fun() called"; }
#include<iostream> };
using namespace std;
int main(void)
class Base
{
{
Derived d;
int x;
public:
d.fun();
virtual void fun() = 0; return 0;
int getX() { return x; } }
};
Output:
// This class inherits from Base and implements fun()
fun() called
Some Interesting Facts:
1. A class is abstract if it has at least one pure
virtual function.
2. We can have pointers and references of
abstract class type.
3. If we do not override the pure virtual function
in derived class, then derived class also
becomes abstract class.
4. An abstract class can have constructors.