2

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).

  • If you only need to expose a few of the parent's methods, why are you using inheritance? – Doval Jun 13 '14 at 13:53
  • @Doval, do you mean that I should be using composition? – Vorac Jun 13 '14 at 14:00
  • 1
    That's the impression I get from the question. Additionally, isn't this C++ specific? Or are there other languages with the concept of "private inheritance"? – Doval Jun 13 '14 at 14:05
  • Composition should normally be preferred over inheritance. There are however times when it makes more sense to use private inheritance. See this question on stackoverflow.com: When to use C++ private inheritance over composition? – David Hammen Jun 13 '14 at 14:40
  • 1
    In a way, private inheritance is sytactic sugar for composition... – Idan Arye Jun 13 '14 at 15:23
3

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().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.