Diamond Inheritance Lowest Base Class Constructor

你说的曾经没有我的故事 提交于 2019-11-26 16:55:41

问题


The Code is as follow :

The Code :

#include <iostream>

using namespace std;

class Animal{
   int a;

    public:
    Animal(int a) : a(a){}
    int geta(){return a;}
};

class Bird : virtual public Animal{
    string b;
    public:
    Bird(int a , string b) : Animal(a) , b(b){}
};

class Fish : virtual public Animal{
    int f;
    public:
    Fish(int a , int f) : Animal(a) , f(f){}
};

class Unknown : public Bird, public Fish{
    char u;
    public:
    Unknown(int a , int f , string b , char u )
     : Bird(a , b) , Fish(a , f) , u(u){}  //Problem
};

The Question :

1.)How am I going to initialize all the superclass if the Unknown class is instantiated?Since there's only one instance of Animal will be created , how can I avoid mysef from having to call its constructor twice ?

Thank you


回答1:


The most derived class initializes any virtual base classes. In your class hierarchy, Unknown must construct the virtual Animal base class (e.g. by adding Animal(a) to its initialization list).

When constructing an Unknown object, neither Fish nor Bird will call the Animal constructor. Unknown will call the constructor for the Animal virtual base.



来源:https://stackoverflow.com/questions/12500230/diamond-inheritance-lowest-base-class-constructor

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