DEV Community

Cover image for Demystifying Virtual and Abstract Functions

Demystifying Virtual and Abstract Functions

Jason C. McDonald on March 02, 2018

EDIT: After some superb comments, I've made some corrections to my original code: (1) virtual destructors, and (2) use of the override and final ke...
Collapse
 
samipietikainen profile image
Sami Pietikäinen

Good introduction to virtual functions! Though there are couple of things I would add. First I would make the base class destructor virtual so the derived class instances are destructed correctly also through base class pointers. Also, in modern C++ (C++11 onwards) it is a good practise to use override keyword in the derived classes. This way the compiler can produce error if the function was not overridden (e.g. missing virtual in base class). It hurts a little inside to see objects not being deleted ;)

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

Hm, TIL. I never encountered override until your comment. I'll start using that, and its cousin final. Thanks! :-)

In the meantime, I've edited to use that in the code above.

Collapse
 
drewmikola profile image
Drew Mikola

Good introduction to the topic, I only have one comment: the destructor of your base class should be marked virtual as well, since it is an inherited class. For the example it doesn't matter, however if both base and derived classes needed to perform unique and specific actions during destruction it will ensure that the object is fully destructed.

Collapse
 
codemouse92 profile image
Jason C. McDonald

Silly me - I should know that! (In my own code, I always do that.) I've edited accordingly.

Collapse
 
eljayadobe profile image
Eljay-Adobe • Edited

The one thing that I've seen developers have trouble grasping is that the advantage of inheritance and polymorphism is code reuse.

Not in the sense of code reuse by the derived class reusing the functions of the base class.

Rather in the sense of users of the base class not having to change their code when given an object of the derived class.

This substitutability is sometimes called the Liskov Substitution Principle.

It's hard to see the value of it in a small contrived example program. But it is an important capability in object-oriented programming for non-trivial programs.

One project I worked on, which been on-going for 10 years by the time I joined the team, had used inheritance for code reuse of the base classes by the dozens and dozens of derived classes. This kind of "code reuse abuse" meant that all the callsites had to check the object to see what type of object was being worked with, so the caller could do the THIS thing rather than the THAT thing with the object. That was a mess.

Collapse
 
codemouse92 profile image
Jason C. McDonald

Ergo one form of what I call "DRY spaghetti". :) Good insight.