Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime cost of inheritance (without virtuality) in C++?

In C++ compiled with -O3, does inheritance without virtuality have a cost in terms of :

  • execution time
  • memory

If the answer is yes : why ?

As an example : are MyClass1 and MyClass2 equivalent in terms of performance and memory ?

enter image description here

like image 386
Vincent Avatar asked Aug 14 '12 17:08

Vincent


People also ask

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.

What are the advantages of using a virtual function in inheritance?

The main advantage of virtual functions are that they directly support object oriented programming. When you declare a function as virtual you're saying that exactly what code is executed depends on the type of the object you call it against. you can't tell exactly what code path it's going to follow.

Why virtual classes are important in the case of multiple inheritance?

Instead, if classes B and C inherit virtually from class A , then objects of class D will contain only one set of the member variables from class A . This feature is most useful for multiple inheritance, as it makes the virtual base a common subobject for the deriving class and all classes that are derived from it.

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.


1 Answers

execution time

Of what? Functions are resolved statically, so function calls are the same. MyClass1's constructor will call the constructors of base classes, and its destructor will call destructors of base classes, so for construction & destruction there may be some overhead. Maybe. Some compilers might optimize the calls away.

memory

This will be the same, both only have a member double. Theoretically. Depends on the implementation I guess, as it's not mandated by the standard, but most commonly there will be no memory overhead.

Note that deleting an object MyClass1 through a pointer to Derived results in undefined behaviour, because there's no virtual destructor.

Note 2 inheritance without polymorphism is a code smell. Not saying it's wrong, but in most cases composition is better.

like image 85
Luchian Grigore Avatar answered Sep 28 '22 17:09

Luchian Grigore