I have a class (the "parent") which has as a member another class (the "child"):
class Engine // THE "PARENT" CLASS
{
public:
// CONSTRUCTOR ------------------------------------
Engine() : mConfig {} // "CHILD" CLASS INITIALIZED HERE
{
// ...
return;
}
// DESTRUCTOR -------------------------------------
~Engine()
{
std::cout << "Engine destructor executing...\n";
// ...
return;
}
private:
GameConfig mConfig; // THE "CHILD" CLASS AS MEMBER OF "PARENT"
};
The "child" class is defined as:
class GameConfig // THE "CHILD" CLASS DEFINITION
{
public:
// ...
// DESTRUCTOR -------------------------------------
~GameConfig()
{
std::cout << "Writing config data...\n";
// ...
return;
}
};
I instantiate the "parent" in main, which in turn (via initializer list) instantiates the "child" class:
int main()
{
Engine gameEngine {};
// ...
std::cout << "Goodbye!\n";
return(0);
}
Based on this question asked on SO, as well as logically, I would have thought the "child" object's destructor would be called before the "parent" object's destructor. But, when I execute this code, the output is:
Goodbye!
Engine destructor executing...
Writing config data...
So the question is: why does a "child" object destructor execute after the "parent" object destructor?