问题
What is the order of constructor call in virtual inheritance in c++?
For the following two cases of multiple inheritance;
(I) for the following code, without virtual inheritance;
class a
{
public:
a()
{
cout<<"\t a";
}
};
class b: public a
{
public:
b()
{
cout<<"\t b";
}
};
class c: public b
{
public:
c()
{
cout<<"\t c";
}
};
class d: public c
{
public:
d()
{
cout<<"\t d";
}
};
class e: public c, public d
{
public:
e()
{
cout<<"\t e";
}
};
class f: public b, public e
{
public:
f()
{
cout<<"\t f";
}
};
int main()
{
f aaa;
return 0;
}
The output is:
a b a b c a b c d e f
(II)With virtual inheritance of class e:
class a
{
public:
a()
{
cout<<"\t a";
}
};
class b: public a
{
public:
b()
{
cout<<"\t b";
}
};
class c: public b
{
public:
c()
{
cout<<"\t c";
}
};
class d: public c
{
public:
d()
{
cout<<"\t d";
}
};
class e: public c, public d
{
public:
e()
{
cout<<"\t e";
}
};
class f: public b, public virtual e
{
public:
f()
{
cout<<"\t f";
}
};
int main()
{
f aaa;
return 0;
}
The output is:
a b c a b c d e a b f
Can someone explain how the output is obtained in both cases? How does virtual inheritance affect the construction of objects?
回答1:
The virtual base class will be initialized firstly, otherwise, the direct base classes will be initialized in left-to-right order of the base class declaration.
For class f
, class f: public b, public e
, there's no virtual base class, the direct base class b
will be initialized at first, then e
. (left-to-right order)
For class f: public b, public virtual e
, the virtual base class e
will be initialized at first, then b
.
See Initialization order:
1) If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)
2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list
3) Then, non-static data members are initialized in order of declaration in the class definition.
4) Finally, the body of the constructor is executed
来源:https://stackoverflow.com/questions/37235368/what-is-the-order-of-constructor-call-in-virtual-inheritance