Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, should I almost always use virtual inheritance?

I see from this entry that virtual inheritance adds sizeof(pointer) to an object's memory footprint. Other than that, are there any drawbacks to me just using virtual inheritance by default, and conventional inheritance only when needed? It seems like it'd lead to more future-proof class design, but maybe I'm missing some pitfall.

like image 361
SuperElectric Avatar asked Dec 28 '10 03:12

SuperElectric


People also ask

When should you use virtual inheritance?

Virtual inheritance is used when we are dealing with multiple inheritance but want to prevent multiple instances of same class appearing in inheritance hierarchy. From above example we can see that “A” is inherited two times in D means an object of class “D” will contain two attributes of “a” (D::C::a and D::B::a).

Should we always use virtual inheritance if yes why if not why not?

The answer is definitely no. The base of an idiomatic answer can be the most fundamental idea of C++: you only pay for what you use. And if you don't need virtual inheritance, you should rather not pay for it. Virtual inheritance is almost never needed.

What happens if we don't use virtual function in inheritance?

If you don't use virtual functions, you don't understand OOP yet. Because the virtual function is intimately bound with the concept of type, and type is at the core of object-oriented programming, there is no analog to the virtual function in a traditional procedural language.

Why should we avoid multiple inheritance?

Multiple inheritance in languages with C++/Java style constructors exacerbates the inheritance problem of constructors and constructor chaining, thereby creating maintenance and extensibility problems in these languages.


2 Answers

The drawbacks are that

  1. All classes will have to initialize all its virtual bases all the time (e.g. if A is virtual base of B, and C derives from B, it also have to initialize A itself).
  2. You have to use more expensive dynamic_cast everywhere you use a static_cast (may or may not be the issue, depending on your system and whether your design requires it).

Point 1 alone makes it not worth it, since you can't hide your virtual bases. There is almost always a better way.

like image 144
Alex B Avatar answered Sep 19 '22 20:09

Alex B


In my experience, virtual inheritance (as opposed to virtual methods) is almost never needed. In C++ it's used to address the "diamond inheritance problem", which if you avoid multiple inheritance cannot actually happen.

I'm pretty sure that I've never encountered virtual inheritance outside C++ books, which includes both code I write and million+ line systems I maintain.

like image 24
Greg Hewgill Avatar answered Sep 21 '22 20:09

Greg Hewgill