Explain virtual base classes?

All QuestionsCategory: Cpp LanguageExplain virtual base classes?
Chetan Shidling Staff asked 5 years ago

I need an explanation.

1 Answers
Best Answer
Chetan Shidling Staff answered 5 years ago

Syntax

class A                            // grandparent
{
……
……
};
class B1 : public A              //parent 1
{
…….
……
};
class B2 : public A               //parent 2
{
……
……
};
class C : public B1,public B2   //child
{
…… //inherits public functions from class A,B1 and B2
};

  1. The child has two direct base classes parent 1 and parent 2 which themselves have a common base class grandparent.
  2. The child inherits the traits of grandparent through two separate paths.
  3. Here the grandparent class is called the indirect base class.
  4. All the public and protected members are inherited twice each via parent1 and parents.
  5. This leads to ambiguity and should be avoided.
  6. Thus the common base class is made as a virtual base class.

syntax

class B1 : public  virtual A              //parent 1
{
…….
…….
};
class B2 : public  virtual A               //parent 2
{
……
…….
};