C++ Abstract Classes and Pure Virtual Functions Explained

To better understand what abstract classes do specifically, we would have to first get a quick refresher on the concepts of inheritance and classes. In a previous discussion, we brought up an analogy of the various workflows inside a typical car production plant. We have also established that classes are similar to the blueprints for the various car parts needed for assembly. Let’s suppose that we are designing a blueprint for a driver-side door for a regular compact sedan. Typically, one would imagine that it would have to come with a few buttons that the driver can press to interact with the various integrated mechanisms, such as window roll-ups, vehicle locking, and rearview mirror adjustments. These functionalities may be basic, but they are the absolute essentials for a typical driver-side door, regardless of the final sticker price of the car. Vehicles with a higher price tag would often come with more functionalities on the driver-side door that expands on these existing basic functionalities, also known as inheritance. Now, it wouldn’t be very practical to write these basic functionalities repeatedly on every single blueprint involving a driver-side door, right? Hence, in this case, the best way forward is to create a master blueprint and codify this standard into driver-side door designs for other car models’ future blueprints. And this is when abstract classes come into play. It acts as an enforcer of those required functionalities and mandates that they must be implemented, regardless of the method of implementation. The enforcement nature is called pure virtual function. Basically, it is a dummy function that does not inherently provide a way of implementation. Instead, it forces other derived classes to make an implementation if you would like to inherit the class member variables or functions inside of this abstract class. We are also able to decipher the meaning of this just based on the name of “abstract class” because the word abstract signifies that this class does not natively provides functionalities, but instead, it is there for one reason and one reason only, to compel the behaviors of its derived classes.

Leave a comment