简体   繁体   中英

Why does a “child” object destructor execute after the “parent” object destructor?

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?

(I'm going to avoid using "parent" and "child" since those terms typically refer to classes that are related by inheritance, not by composition.)

Destroying a C++ object involves executing its destructor's body and additional destruction work that is automatically generated by the compiler, such as destroying member objects and invoking base class destructors.

That additional work must happen after the the destructor's body is invoked. If it instead happened before, the containing object's destructor would not be able to do anything with its members, which in most cases would make the destructor useless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM