0

I am new into C++ and I am currently learning it.
While I was exploring web and problems I came across on next code:

class A
{
    public:
    ~A() { cout << "A"; }

};

class B
{
    public:
        ~B() { cout << "B"; }
};


int main()
{
    A a;
    B b;

    return 0;
}

Output of looks like this:

BA

Can somebody explains why output looks like this?

Strahinja
  • 440
  • 9
  • 26

3 Answers3

6

Cleaning up the myth in other answers: no, cleanup order has nothing to do with a stack.

The C++ standard does not even define the concept of a stack except in two circumstances:

  • stack unwinding (as a process).
  • the stack container adapter.

Neither is relevant here. What is relevant though is section 6.6:

On exit from a scope (however accomplished), objects with automatic storage duration that have been constructed in that scope are destroyed in the reverse order of their construction.

Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of objects with automatic storage duration that are in scope at the point transferred from but not at the point transferred to.

The fact most architectures implement this behavior using an execution stack is a “happy coincidence”, but it is not mandated by the standard.

On the other hand reverse order destruction is guaranteed, regardless of whether the implementation will use a stack or not.

spectras
  • 13,105
  • 2
  • 31
  • 53
  • 1
    even more, even on implementation where the stack is used - it is used for function call stacking, it has nothing to do with lifetime within a scope. Maybe for nested scopes. – bolov Oct 28 '18 at 14:30
  • Indeed, in fact in the example in OP's question, most likely if optimizations are enabled the stack isn't touched at all within `main`. Perhaps for calling into the c++ runtime… – spectras Oct 28 '18 at 14:34
  • That's what I thought so but couldn't find that info. Thanks! :) – Strahinja Oct 28 '18 at 15:50
3

Objects are destroyed in the reverse order of their creation.

OznOg
  • 4,440
  • 2
  • 26
  • 35
0

The objects in a function are allocated memory in a heap if they are created using the new keyword.Dynamic Memory

The objects in a function are allocated memory in a stack (although c++ doesn't mandate that a stack is used) if they are not created using the new keyword.

int main( )
{
    A a;
    B b;
} 

In the above case B is on top of A. Hence it is destroyed first once the function ends. We call destructor to destroy the memory allocation. more

Additional resource: similar question

Pavithran Ravichandiran
  • 1,711
  • 1
  • 17
  • 20