Is the order of destruction well defined in the case of multiple inheritance?
struct A
{
~A(){std::cout << "A\n";}
};
struct B
{
~B(){std::cout << "B\n";}
};
struct AB : public B, public A
{
~AB(){std::cout<<"AB\n";}
};
int main()
{
AB ab;
}
For the given code my compiler prints:
AB
B
A
But I use more complex constructs (including CWinApp
), I get different results. So is the order well-defined? And if so, what is the ordering rule?
From [class.dtor]:
Bases and members are destroyed in the reverse order of the completion of their constructor (see 12.6.2).
The constructor ordering, from [class.base.init]:
In a non-delegating constructor, initialization proceeds in the following order:
— First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized [ ... ]
— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
For your example:
struct AB : public B, public A
The construction order is B
then A
then AB
. So the destruction order is AB
then A
thenB
.