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 ?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With