Inheritance wrong call of constructors [duplicate]

試著忘記壹切 提交于 2019-12-11 06:25:29

问题


I'm implemeting this diamond inheritance:

class Object {
private:
    int id; string name;
public:
    Object(){};
    Object(int i, string n){name = n; id = i;};
};


class Button: virtual public Object {
private: 
    string type1;
    int x_coord, y_coord;
public:
    Button():Object(){};
    Button(int i, string n, string ty, int x, int y):Object(i, n){
          type = ty;
          x_coord = x;
          y_coord = y;};
};


class Action: virtual public Object {
private:
    string type2;
public:
    Action():Object(){};
    Action(int i, string n, string t):Object(i, n){ type2 = t;};
};


class ActionButton: public Button, public Action{
private:
    bool active;
public:
    ActionButton():Buton(), Action(){};
    ActionButton(int i, string n, string t1, int x, int y, string t2, bool a):
    Button(i, n, t1, x, y), Action(i, n, t2) {active = a;};
};

Everything works fine about the first three classes, but when I try to create an object of the type ActionButton, instead of calling the constructor with the parameters I wrote, it is calling the default one from the class Object. So every ButtonAction object has name an empty string and id a random value. What's wrong with my code and how can i make it work properly?


回答1:


Virtual bases are constructed directly by the constructor of the most derived class.

Your ActionButton constructor doesn't explicitly call Object's constructor, so the default constructor is called for you.



来源:https://stackoverflow.com/questions/38104855/inheritance-wrong-call-of-constructors

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