This is an advanced C++ topic so don’t get worried if it’s difficult right now. You’ll rarely need to use private inheritance. And protected inheritance is probably even more rare. Some of my programming books just say that this whole topic is “beyond the scope of this book”. I’ll do my best to explain this concept because that’s what this podcast is all about. You get to learn from my experience.
If you’re using C#, Java, or some other language that doesn’t support private inheritance, then you’ll have to write your code differently. But even then, understanding this will help you. Once you understand private inheritance, then protected inheritance really gives you the same ability that extends to other derived classes.
If you’re not familiar with this topic or research some online forums, you’ll likely wonder why you just can’t use composition. So instead of inheriting from some class that you don’t want to make that relationship public, you instead declare a member variable in your class of the other base class. This is called composition and will be the topic of another episode.
Effectively, private inheritance and protected inheritance give you a new type of relationship. Instead of the public IS-A relationship, you can think of this new relationship as an IS-IMPLEMENTED-AS relationship.
Inheriting gives you three main benefits that you don’t get with composition:
1. You can access public and protected members in the other class. You’re limited to just the public members with composition.
2. You can override methods in the other class. This is still inheritance even if it is private or protected.
3. You can take advantage of a special compiler optimization that only applies to inheritance. It’s called the empty base class optimization. You don’t get this benefit unless it really is a base class.