Unexpected inaccessible base (first derived class)

拟墨画扇 提交于 2020-01-07 04:19:07

问题


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:


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.



来源:https://stackoverflow.com/questions/44488533/unexpected-inaccessible-base-first-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!