I want to know what a ‘virtual base class‘ is and what it means.
Let me show an example:
class Foo { public: void DoSomething() { /* ... */ } }; class Bar : public virtual Foo { public: void DoSpecific() { /* ... */ } };
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.