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

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

  • lead time
  • memory

If so, why?

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

enter image description here

+6
source share
2 answers

lead time

What? Functions are solved statically, so function calls are the same. The constructor of MyClass1 calls the base class constructors, and its destructor will call the base class destructors, so there may be some overhead for building and destroying it. May be. Some compilers can optimize calls.

of memory

It will be the same, both will only have a double member. In theory. Depends on the implementation, I believe, since it is not provided by the standard, but most often there will be no memory overhead.

Note that deleting the MyClass1 object with a pointer to Derived leads to undefined behavior because there is no virtual destructor.

Note 2 Inheritance without polymorphism is the smell of code. Not to say it wrong, but in most cases the composition is better.

+8
source

As for memory space, I think your MyClass1 consumes more, because it needs to keep track of the whole structure and class relationships. For execution, I do not see a noticeable difference.

-3
source

Source: https://habr.com/ru/post/922864/


All Articles