15

g++ is denying me access to a type, just because it happens to be a private grand-father. Does this make sense?

struct A {};

struct B : private A {};

struct C : B {
  void foo(A const& a) {}
};

Compiling this yields:

1:10: error: ‘struct A A::A’ is inaccessible
6:12: error: within this context

My point is: I never wanted to access A as an ancestor. In fact, if A is a private ancestor of B, shouldn't this be completely invisible to anybody but B (i.e. C)?

Of course, I could use protected inheritance but in my case it doesn't really make sense.

bitmask
  • 32,434
  • 14
  • 99
  • 159

2 Answers2

14

This is due to the injected class name from A hiding the global A inside C. Although A is visible, it is not accessible (since it is imported as private), hence the error. You can access A by looking it up in the global namespace:

void foo(::A const& a) {}
avakar
  • 32,009
  • 9
  • 68
  • 103
8

if you declare it as follows it works

struct A {};

struct B : private A {};

struct C : B {
  void foo(::A const& a) {}
};

The error your seeing is do to name resolution not access. The ::A says look at the global namespace not my inherited nested class types. Also remember that private inheritance is just saying B has an A and IMOHO is a stupid language feature that should be avoided.

rerun
  • 25,014
  • 6
  • 48
  • 78
  • 1
    It's not a stupid feature at all; it allows one to restrict the inherited interface by individually picking out the functions to expose with `using`. – avakar Nov 04 '11 at 15:00
  • 2
    Which you could do with forwarder functions with out the feature and making the c++ inheritance model less cluttered. private inheritance is not inheritance its composition and using the same semantics to accomplish two separate concepts is only confusing. – rerun Nov 04 '11 at 15:05
  • 2
    It's a difference between composition and private inheritance, because the latter allows you access to protected members of your father while the former doesn't. – bitmask Nov 04 '11 at 15:12
  • I still wouldn't suggest using it except in that case. – rerun Nov 04 '11 at 19:25