C++ Telltales part 5:
Protected and Private Inheritance
This is fifth part of my C++ Telltales series where I share some tips and tricks to work with C++. Feel free to check out also other parts of the series here!
If you are working with C++ you must be familiar with class inheritance (or if not, you really should put it on top of your bucket list). It’s very often you use public inheritance without even thinking about it but there is actually two other ways to inherit the parent class: protected and private. But what do they actually mean? Well, let’s try to let the code talk for us:
As explained in the comments of the main function, the public functions of the BaseClass will have the same visibility as the inheritance visibility is. This also applies to the member variables of the classes.
So where should this be used then? Well, if you want to hide some public functions from the caller but still like to have them available for the inheriting classes. Especially with protected inheritance you can create quite interesting designs. Here is a table showing the different inheritance options and how they affect the inheriting class: