开发者

c++ inheritance: error C2614 calling base class' constructor

开发者 https://www.devze.com 2023-04-09 22:53 出处:网络
I have a bas开发者_开发问答e class \'A\' which has a subclass \'B\' which has a subclass \'C\' which has a subclass \'D\'.

I have a bas开发者_开发问答e class 'A' which has a subclass 'B' which has a subclass 'C' which has a subclass 'D'.

I want D to call 'A's constructor,

D(int x,int y):A(x,y){};

but I am getting the error message: error C2614: 'D' : illegal member initialization: 'A' is not a base or member.

D can call any of 'C's constructors fine but that is not what I want. Any help would be super appreciated.


You're stuck, that's the way C++ works - you only get to call the constructor of your immediate parent. You can daisy chain them so that D calls C's constructor which calls B's constructor which calls A's constructor.

D(int x,int y):C(x,y){};
C(int x,int y):B(x,y){};
B(int x,int y):A(x,y){};


As Mark Ransom's answer states, a derived class is only allowed to call its base class' constructor.

In your case, you can solve the problem by passing along the constructor arguments to D down the inheritance hierarchy until A's constructor is called by B with those arguments.

Another option is to create a protected function, say A::init( args ) that can be called by D directly.


In addition to the option of passing arguments down the inheritance hierarchy or having a protected member function in the base class, you could also solve this by using virtual inheritance. With virtual inheritance all base class constructors are called directly from the derived class so you don't have to go through the inheritance chain.

class A
{
public: A(){}
public: A(int x, int y){}
};

class B : public virtual A
{
public: B(){}
};

class C : public virtual B
{
public: C(){}
};

class D : public virtual C
{
public: D(int x,int y):A(x,y){};
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号