Dmitry J Dmitry J - 1 year ago 100
C++ Question

Is-a relationship without virtual functions c++

I couldn't find examples of is-a relationship without virtual functions. Is a following pattern ok?

class Base {
void doSomethingWithX() {/*implementation here*/}
int x_;

class Derived : public Base {
//Add some other functionality but inherit doSomethingWithX and its implementaion
void doSomethingWithY();
~Derived(); //And document that nobody should inherit further from this class.
int y_;

foo(Base* ptr) {
//Do something via Base interface

Derived d;

Edit: I was asked to clarify what I mean by "is this pattern ok".
Does this kind of inheritance satisfies what is usually needed from is-a relationship? Liskov substitution principle etc.
Is it safe to use Derived objects via pointer to Base? (or I miss some problem here).

I'm asking this because there is often written that base class destructor should be either public and virtual or protected and non-virtual. But I never met real examples of public inheritance without non-virtual functions.

Answer Source

It's okay for what you're doing here; You can pass a pointer to Derived and it can bind to a pointer of Base just fine. It's not possible to say whether it satisfies the Liskov subtitution principle because we do not know the invariants of your classes.

Just recognize that without any virtual functions, you cannot use polymorphism. This goes beyond simply overriding function behavior; you'll never be able to perform a dynamic_cast of a pointer to Base to a pointer to Derived.

Additionally, if nobody should derive from Derived, then mark it final, which is available since C++11

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download