Virtual base class and initialization lists

Possible duplicate:
gcc C ++ virtual inheritance problem

Hello everybody,

I am wondering how the compiler will handle different initialization values ​​when using multiple inheritance from a virtual base class. Consider the notorious diamond of fear inheritance scheme:

     Base
     / \
    /   \
  D1     D2
    \   /
     \ /
     Join

To avoid having two copies Basein Join, I use virtual inheritance for D1and D2(see, for example, here ). Now let's say that Baseit is not abstract, but has a member field that is initialized in its constructor:

class Base { 
public:
    Base(int x_) {x = x_;};
    virtual ~Base(){};

public:
    int x;
};

class D1 : public virtual Base {
public:
    D1() : Base(1) {};
    virtual ~D1(){};
};

class D2 : public virtual Base {
public:
    D2() : Base(2) {};
    virtual ~D2(){};
};

class Join : public D1, public D2 {
public:
    Join(){};
    ~Join(){};
};

int main()
{
   Join j;
   cout << j.x << endl;

   return 0;
}

Will there be output 1, 2, or does it depend on the compiler?

+3
source share
3

. , Join. Join Base, Base .

[ , ;, , . main int, , j.x j->x.]

+5

, , .

Join Base:

   class Join : public D1, public D2 
    {
    public:
        Join() : Base(3){} // or whatever value
        ~Join(){}
    };

, .

( main int, j->x not j.x, j - , , delete , new > )

+2

Since the base does not have an implicit constructor, and both C1and C2are virtual database, you will have to change their way (and also add a semicolon after the rest of the class declarations, as indicated by Charles Bailey)

class Join : public D1, public D2 {
public:
    Join() : Base(3) {};
    ~Join(){};
};

int main()
{
   Join j;
   cout << j.x << endl;
}

Then it prints 3to standard output

+1
source

Source: https://habr.com/ru/post/1788934/


All Articles