1

Why does Downnot invoke the Base ctor through Left & Right twice?

class Base {
public:
    Base() { cout << "base-ctor" << endl; }
    Base(string a) { cout << a << endl; }
};

class Left : virtual public Base {
public:
    Left(string a) : Base(a) {}
};

class Right : virtual public Base {
public:
    Right(string a) : Base(a) {}
};

class Down : public Left, public Right {
public:
    Down(string a) : Left(a), Right(a) {}
};

int main() {
    Down x("down");
    // -> base-ctor
}
0ax1
  • 475
  • 3
  • 11

2 Answers2

1

Because you are using virtual inheritance from base class:

class Left : virtual public Base {
class Right : virtual public Base {

if you want to have it invoced twice, remove the virtual keyword:

class Left : public Base {
class Right : public Base {

This article might be useful for you, if you want to avoid a 'diamond problem': http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem

szulak
  • 703
  • 7
  • 16
0

Why should it? That it does not is literally the whole point of virtual inheritance, which you've opted to use in your code sample. I guess you decided to use it without researching what it does.

As for this behaviour being "incorrect", well, by definition it is your expectation that is incorrect.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055