virtual public inheritance? Need help understanding code

I have question about virtual inheritance. I'm interested why this code prints 1000 (from class "two") and not 3 (from class "one")

here's the code:

#include <iostream>
using namespace std;

class A {
protected:
    int number;
public:
    A (int a=0) {number=a;}
};

class one:virtual public A {
public:
    one (int a=3) {number=a;}
    void print()  {cout<<number<<endl;}
};

class two :virtual public A {
public:    
    two (int a=1000) {number =a;}
    void print() { cout<<number<<endl; }
};

class B:public one,public two {
public:
    void print() { cout<<number<<endl; }
};

int main () {
    B A;
    A.print();
}

Upvotes: 0

Views: 64

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254471

The base classes are initialised in the order they are declared: one then two. The virtual inheritance means that they both share the same instance of A, so there is only one variable called number here.

Initialising one assigns 3 to number then initialising two assigns 1000 to it. So, after initialising the whole object, it ends up with the value 1000.

Upvotes: 2

Related Questions