Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

c++ - Diamond Inheritance Lowest Base Class Constructor

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...