C++ Inheritance – Public vs Private Inheritance for Exposing Parent’s Methods

c++11encapsulationinheritance

Public inheritance means that all fields from the base class retain their declared visibility, while private means that they are forced to 'private' within the derived class's scope.

What should be done if some of the parent's members (say, methods) need to be publicly exposed?

I can think of two solution. Public inheritance somewhat breaks encapsulation. Furthermore, when you need to find out where is the method foo() defined, one needs to look at a chain of base classes.

Private inheritance solves these problems, but introduces burden to write wrappers (more text). Which might be a good thing in the line of verbosity, but makes changes of interfaces incredibly cumbersome.

What considerations am I missing? What constraints on the type of project are important? How to choose between the two (I am not even mentioning 'protected')?

Note that I am targeting non-virtual methods. There isn't such a discussion for virtual methods (or is there).

Best Answer

You can expose items that would otherwise have some kind of restricted access (i.e., private or protected) without writing a wrapper function by using the using directive:

class base {
public:
    base();
    virtual ~base();
    void do_something();
    void do_something_else();
private:
    // elided
};

class derived : private base {
public:
    derived();
    virtual ~derived();
    using base::do_something();
};

In the above, the derived class exposes base::do_something() as a public method, but not base::do_something_else().

Related Topic