Consider the following piece of code
#include<iostream>
#include<string>
class A
{
private:
char name[10];
public:
A() { }
A(const char *str)
{
strcpy(name, str);
std::cout<<name<<" constructed"<<endl;
}
~A()
{
std::cout<<name<<" destructed"<<endl;
}
};
int main()
{
A a("a");
A b("b");
return 0;
}
O/P of the following programs comes out to be:
a constructed
b constructed
b destructed
a destructed
The only explanation I have for the above code is that since b was created after a, it should be stored above a in the stack. Now when the main finishes, b was poped out first and then a, hence its destructor got called first and then of a‘s.
My question is: Am I correct in thinking so or the above is an undefined behavior and may varies from compiler to compiler?
It does not vary, objects in automatic memory (stack) are destructed in reverse order in which they are created. It’s fully specified by the standard.
C++03 15.2. Constructors and destructors