PPC
PPC

Reputation: 19

Is destructor called at the end of main(); strange behavior

// Foo.h

class Foo
{

public:
    Foo();
    ~Foo();
    void exec();
};


// Foo.cpp

Foo::~Foo()
{
    // Statements A
    exit(0);
}

//main.cpp

int main()
{
    Foo foo;
    foo.exec();

    // Statements B
    return 0;
}

So why both Statements A and B get executed? And is the destructor called when we reach return 0?

I have seen variants where void exec(); is int exec(); and the main function ends with
return foo.exec(); does this calls the destructor?

Because I want to have an object that takes control of the code flow from the main function and end the program later.

Upvotes: 1

Views: 3331

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

The destructor is called once the main function returns, i.e. after the return statement, just like local objects in any other function.

As for return someObject.someFunction();, the expression in the return statement must be fully evaluated before the return statement can actually return anything, because it needs the result of that expression. So if the function contains a long-running loop (like a GUI event loop) then it might take quite some time before the return statement actually returns.

Upvotes: 2

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145269

The destructor, and hence statement A, is executed as part of the processing of the return 0 statement B. This is a simple guarantee in C++, that the destructor of a local object with automatic storage, is executed automatically when the execution leaves the object's scope.

Upvotes: 2

Related Questions