Abstract Classes and Polymorphism Revisited

I’m on a fundamentals trip at the moment, so I’m going back over things I mostly understand to ensure I really understand the principles involved and not just in a vague hand-waving kind of way. Today’s fundamental revisited is abstract (pure virtual) classes and polymorphism in C++ – it’s commented to the hilt to make clear not only what’s going on but WHY it’s going on. You wouldn’t generally comment your code this heavily, but as a reminder/guide I’m fine with it:

What would happen if we did NOT declare Shape as an abstract class? Well, we’d have to provide implementations for the type(), area() and perimeter() methods for Shape – but that’s about it. The polymorphism part would still work, that is, we could still create an array of pointers to a Shape, and then instantiate each shape as a Circle or a Rectangle as we see fit – and the correct functions would execute for each derived class.

However, it makes good sense to declare Shape as an abstract class so that we can’t instantiate it (even if we wanted to), in the same way that we’d make a Car class abstract. You can’t go out and buy a Car – it’s generic. You can buy a Ford Escort, or a Hyundai i30 or even a Ferrari F40, but you can’t buy a car in the same way that you can’t (technically) eat food or drink beer.

Doesn’t stop me trying though. Cheers! =D

Leave a Reply

Your email address will not be published.