patterncppCritical
In C++, what is a virtual base class?
Viewed 0 times
baseclasswhatvirtual
Problem
I want to know what a "virtual base class" is and what it means.
Let me show an example:
Let me show an example:
class Foo
{
public:
void DoSomething() { /* ... */ }
};
class Bar : public virtual Foo
{
public:
void DoSpecific() { /* ... */ }
};Solution
Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritance.
Consider the following scenario:
The above class hierarchy results in the "dreaded diamond" which looks like this:
An instance of D will be made up of B, which includes A, and C which also includes A. So you have two "instances" (for want of a better expression) of A.
When you have this scenario, you have the possibility of ambiguity. What happens when you do this:
Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your classes, you're telling the compiler that you only want a single instance.
This means that there is only one "instance" of A included in the hierarchy. Hence
This is a mini summary. For more information, have a read of this and this. A good example is also available here.
Consider the following scenario:
class A { public: void Foo() {} };
class B : public A {};
class C : public A {};
class D : public B, public C {};The above class hierarchy results in the "dreaded diamond" which looks like this:
A
/ \
B C
\ /
DAn instance of D will be made up of B, which includes A, and C which also includes A. So you have two "instances" (for want of a better expression) of A.
When you have this scenario, you have the possibility of ambiguity. What happens when you do this:
D d;
d.Foo(); // is this B's Foo() or C's Foo() ??Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your classes, you're telling the compiler that you only want a single instance.
class A { public: void Foo() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};This means that there is only one "instance" of A included in the hierarchy. Hence
D d;
d.Foo(); // no longer ambiguousThis is a mini summary. For more information, have a read of this and this. A good example is also available here.
Code Snippets
class A { public: void Foo() {} };
class B : public A {};
class C : public A {};
class D : public B, public C {};A
/ \
B C
\ /
DD d;
d.Foo(); // is this B's Foo() or C's Foo() ??class A { public: void Foo() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};D d;
d.Foo(); // no longer ambiguousContext
Stack Overflow Q#21558, score: 601
Revisions (0)
No revisions yet.