Vincent
Vincent

Reputation: 60381

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

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

If the answer is yes : why ?

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

enter image description here

Upvotes: 7

Views: 969

Answers (2)

flyree
flyree

Reputation: 29

In terms of memory space, I guess your MyClass1 consumes more because it needs to keep track of all class structure and relations. For performance I don't see any notable difference.

Upvotes: -3

Luchian Grigore
Luchian Grigore

Reputation: 258598

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.

Upvotes: 8

Related Questions