c++inheritance

How often is non-public C++ inheritance used in practice?


Possible Duplicate:
When should I use C++ private inheritance?

I wanted to make this community-wiki but don't see the button... can someone add it?

I can't think of any case I've derived from a class in a non-public way, and I can't recall off-hand seeing code which does this.

I'd like to hear real-world examples and patterns where it is useful.


Solution

  • Your mileage may vary...

    The hard-core answer would be that non-public inheritance is useless.

    Personally, I use it in either of two cases:

    In either cases, I thus use private inheritance because the inheritance itself is an implementation detail.

    I have seen people using private inheritance more liberally, and near systematically, instead of composition when writing wrappers or extending behaviors. C++ does not provide an "easy" delegate syntax, so doing so allow you to write using Base::method; to immediately provide the method instead of writing a proper forwarding call (and all its overloads). I would argue it is bad form, although it does save time.

    1 The Empty Base Optimization was rendered obsolete in C++20 with the addition of the [[no_unique_address]] attribute.