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
269 views
in Technique[技术] by (71.8m points)

c++ - Order of constructor call in virtual inheritance

class A {
        int i;
public: 
        A() {cout<<"in A's def const
";};
        A(int k) {cout<<"In A const
";  i = k; }
        };

class B : virtual public A {
public:
        B(){cout<<"in B's def const
";};
        B(int i) : A(i) {cout<<"in B const
";}
        };

class C :   public B {
public:
        C() {cout<<"in C def cstr
";}
        C(int i) : B(i) {cout<<"in C const
";}
        };

int main()
{
        C c(2);
        return 0;
}

The output in this case is

in A's def const
in B const
in C const

Why is this not entering into in A const

`It should follow the order of 1 arg constructor call. But what actually is happening on deriving B from A using virtual keyword.

There are few more question

Even if I remove the virtual keyword in above program and remove all the default constructor it gives error. So, why it needs the def constructor

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The constructors for virtual base classes are always called from the most derived class, using any arguments it might pass in. In your case, the most derived class doesn't specify an initializer for A, so the default constructor is used.


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

...