0
votes

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;
   public: 
   B() { i=1; }
  int get_i() { return i; }
};
class D: private B  
{ int j;
  public:
   D() { j=2; }
  int get_j() {return j; }
 };
 int main()
 { 
 B *p= new D; 
 return 0;
 }

Thank you!

1
Thank you for your answer! Can you please post this as an answer so i can check this question as solved?Eduard6421

1 Answers

0
votes

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.