user997112
user997112

Reputation: 30615

Polymorphism vs regular inheritance?

I use polymorphism so frequently, but it suddenly dawned upon me. I have the case where my code is:

class A{

class B : public A{

class C : public A{

and I use class A as a polymorphic parameter type for passing in B or C sub types:

//Accepts B and C objects
void aMethod(A* a){

However, I gave A a virtual destructor- this is the only reason A (and B and C) contain a vtable pointer.

So my question is, if I hadn't declared A with a virtual destructor, then A wouldn't be polymorphic- I wouldn't be able to pass objects of type B or C in aMethod()??

So is non-polymorphic inheritance just about sharing code, whereas polymorphism (the base class must have a vtable) allows passing sub types as arguments of the base class type?

Upvotes: 0

Views: 330

Answers (3)

Walter
Walter

Reputation: 45424

A class with its destructor the only virtual method, like your class A, is an oddity. AFAIK, such a class has no necessity in well designed code.

From your question, it is not clear whether the virtual destructor is needed (i.e. if you ever call the destructor of classes B or C through a reference or pointer to class A), but if it is, your code smells. If it is not, then simply make the destructor non-virtual.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283624

Non-polymorphic types also contain a subobject for each base class, and upcasts are still implicit.

You can therefore pass objects of derived classes just fine even when there is no polymorphism. The receiver will act on the base subobject, just as happens for data members and non-virtual functions of polymorphic types.

Upvotes: 0

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145239

In this code you provide,

void aMethod(A a){

the a formal argument is not polymorphic. It's passed by value. When you pass in a B or C object as actual argument, you're just slicing it down to an A, that is, you're copying the A base class sub-object only.


Regarding

So is non-polymorphic inheritance just about sharing code, whereas polymorphism (the base class must have a vtable) allows passing sub types as arguments of the base class type?

it combines two questions that have to be treated separately.

Inheriting from a non-polymorphic class is about sharing of code, yes, but it also introduces an is-a relationship, which can be important for e.g. passing by reference.

Inheriting from a polymorphic class (one with one or more virtual member functions) allows you to override base class functionality, or to implement it where the base class leaves that as a derived class responsibility – typically by having pure virtual member functions. This means that member functions in the base class can call your derived class’ member functions. Also, that calling member functions via a base class pointer or reference, can call your derived class’s implementations.

Upvotes: 2

Related Questions