The construction algorithm now works as follows:
virtual bases have the highest precedence. Depth comes next, and then the order of appearance; leftmost bases are constructed first.
Order of Destructors is just reverse of Construction.
Algorithm:
1. Construct the virtual bases using the previous depth-first left-to-right order of appearance. Since there's only one virtual base B, it's constructed first.2. Construct the non-virtual bases according to the depth-first left-to-right order of appearance. The deepest base specifier list contains A. Consequently, it's constructed next.
3. Apply the same rule on the next depth level. Consequently, D is constructed.
4. Finally, D2's constructor is called.
Examples:
Example1:
class Base
{
public:
Base() { cout<<"\n Base C'ctor\n"; }
};
class Derived1 : virtual public Base
{
public:
Derived1() { cout<<"\n Derived1 C'ctor\n"; }
};
class Derived2 : virtual public Base
{
public:
Derived2() { cout<<"\n Derived2 C'ctor\n"; }
};
class Derived3 : public Derived1, public Derived2
{
public:
Derived3() { cout<<"\n Derived3 C'ctor\n"; }
};
main()
{
Derived3 d;
}
Output:
Base C'ctor
Derived1 C'ctor
Derived2 C'ctor
Derived3 C'ctor
Example2:
class Base
{
public:
Base() { cout<<"\n Base C'ctor\n"; }
};
class Derived1 : public Base
{
public:
Derived1() { cout<<"\n Derived1 C'ctor\n"; }
};
class Derived2 : public Base
{
public:
Derived2() { cout<<"\n Derived2 C'ctor\n"; }
};
class Derived3 : public Derived1, virtual public Derived2
{
public:
Derived3() { cout<<"\n Derived3 C'ctor\n"; }
};
main()
{
Derived3 d;
}
Output :
Base C'ctor
Derived2 C'ctor
Base C'ctor
Derived1 C'ctor
Derived3 C'ctor
Example3:
class Base
{
public:
Base() { cout<<"\n Base C'ctor\n"; }
};
class Derived1 : public Base
{
public:
Derived1() { cout<<"\n Derived1 C'ctor\n"; }
};
class Derived2 : virtual public Base
{
public:
Derived2() { cout<<"\n Derived2 C'ctor\n"; }
};
class Derived3 : public Derived1, public Derived2
{
public:
Derived3() { cout<<"\n Derived3 C'ctor\n"; }
};
main()
{
Derived3 d;
}
Output:
Base C'ctor
Base C'ctor
Derived1 C'ctor
Derived2 C'ctor
Derived3 C'ctor
Link:
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=169