James Dickens James Dickens - 2 months ago 21
C++ Question

Protected class inheritance in C++

The following code is giving me the error that 'A' is an inaccessible base of 'B' and I am not sure why:

class A {};
class B : protected A {};
A foo( A a );
///
B b;
foo(b);


Any explanation for this much appreciated.

Edit: I suppose I am just confused about the nature of protected inheritance. I thought it meant that any derived class (in this case of A) could inherit its variables and its functions.

Answer

A class that inherits the protected parent class can get to it, otherwise it is considered private:

class A {};
class B : protected A {};
A foo(A a) { return a; };
class C : public B {
public:
    A foo(C c) { return c; };

};

int main() {
    B b;
    //foo(b); // Can't implicitly convert, A is protected (might as well be private from this line's perspective)
    C c;
    A a = c.foo(c); // class C can get A
}