What is Virtual Inheritance ?

  • During multiple inheritance Virtual Inheritance is used to remove the ambiguity of base class, when a derived class inherits the same base class via other classes in C++.

  • For example, we consider four classes A, B, C, and D.
  • If an object of type D tries to access members of A, ambiguity arises as to which class it should resolve.
  • If it is class D that C inherited or it is class D that B inherited as a result, compiler throws an error.
  • We declare that B and C inherit A virtually, to remove this ambiguity.
  • It ensures that an object of type D will contain only set of member variables from A.

Sample Code

[pastacode lang=”cpp” manual=”using%20namespace%20std%3B%0A%20%0Aclass%20A%20%7B%0Apublic%3A%0A%20%20%20%20int%20x%20%3D%202%3B%0A%7D%3B%0A%20%0Aclass%20B%3A%20public%20virtual%20A%20%7B%0A%7D%3B%0A%20%0Aclass%20C%3A%20public%20virtual%20A%20%7B%0A%7D%3B%0A%20%0Aclass%20D%3A%20public%20B%2C%20public%20C%20%7B%0A%7D%3B%0A%20%0Aint%20main()%20%7B%0A%20%20%20%20D%20d%20%3D%20D()%3B%0A%20%20%20%20cout%20%3C%3C%20%22x%20%3A%20%22%20%3C%3C%20d.x%20%3C%3C%20endl%3B%0A%7D%0A” message=”” highlight=”” provider=”manual”/]

Output

Leave a Reply

Your email address will not be published. Required fields are marked *