Search code examples
c++inheritanceprivate-inheritance

What is private inheritance, and what issues(s) does it address?


Could someone explain what exactly private/protected inheritance in C++ is for, and what problem(s) it is intended to solve?

class Bar { };
class Foo : private Bar { };

I've already seen this question but I still don't understand what it is, let alone when I should use it.

(Comparison to features in Java/C# or similar languages could also be helpful.)


Solution

  • The private inheritance models "is-implemented-in-terms-of". The meaning is similar to "has-a". The differences are:

    1. With private inheritance you don't need to write a wrapper (good for lazy programmers)

    2. "has-a" allows you better control, you can expose only a subset of the interface or change method names if you like.

    3. Private inheritance makes exception safety difficult, have a look at exceptional c++ for more information

    4. You really need private inheritance just when you want to use a protected members of your base class.

    5. Sometimes private inheritance is used in the mix-in class (Effective c++ memory management chapters)

    My personal preference is using "has-a" for general purpose, I use private inheritance just after I have rule out other options.