Eduard6421 Eduard6421 -4 years ago 87
C++ Question

Unexpected inaccessible base (first derived class)

The following code gives the error: 'B' is an inaccessible base of 'D'.

Why does this happen? The constructor of B is public which means it should be inherited by class D even though the inheritance is protected / private.

Can someone tell me a workaround as well? Except of course making the inheritance public.

#include <iostream>
#include <typeinfo>
using namespace std;
class B
{ int i;
B() { i=1; }
int get_i() { return i; }
class D: private B
{ int j;
D() { j=2; }
int get_j() {return j; }
int main()
B *p= new D;
return 0;

Thank you!

Answer Source

Your example could be narrowed to

D * p_d{nullptr};
B * p_b{p_d};

Casting to private base class is prohibited outside of derived class and derived class's friends scope. Error has nothing to do with constructor (which will work as expected).

You may also want to check some workarounds.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download