5

C++ supports protected inheritance: A class can derive from a base class B in a way that the "outside" world doesn't see that class "as a B" but the class itself and it's derived classes does see itself "as a B".

struct B {};
struct Klass : protected B {
  // here I am B
};
struct Derived : public Klass {
  // here I am B
};

// ... Klass k; // k is not a B Derived d; // d is not a B

(Demo)

Is there any use to this language feature? I'm specifically looking for patterns / functionality which is easy to implement with protected inheritance, but difficult (or "ugly", verbose) without it.

Similar to this question, but none of the answers there really apply here IMO. Interest sparked by this stackoverflow question.

1 Answers1

2

There are (or at least should be) no applications where this feature is actually useful. The reason for this is that the only thing it allows you to do is this:

class A : protected B {
   ...
   void something () { doSomethingThatRequiresB(this); }
};

But this is exactly equivalent to:

class A {
protected:
   B myB;
   ...
   void something () { doSomethingThatRequiresB(&myB); }
};

The latter, however, is easier to understand so is always preferable.

The only caveat is that, per the answer referenced in Doc Brown's comment to the question, it appears in some circumstances (particular if the base class is empty) the former can trigger some optimisations that the latter does not, but at least theoretically they should be the same, and I would consider the lack of optimisation in the latter case a shortcoming of the compiler, not a problem of the code.

occipita
  • 209