MMMMMCK
MMMMMCK

Reputation: 337

Order of Destructor Calling When Leaving Scope? (C++)

I'm trying to understand the order of destructor calling when dropping out of scope. Let's say I have the following code:

class Parent{

Parent(){cout<<"parent c called \n";}
~Parent(){cout<< "parent d called \n";}
};

class Child: public parent{

Child(){cout<< "child c called \n";}
~Child(){cout<<"child d called\n";}
};

Now, I know that the child constructor and destructor is derived from the parent, so the following main:

int main(){

Parent Man;
Child Boy;

return 0;
}

Would produce the output:

parent c called
parent c called
child c called
... //Now what?

But now, what happens when I drop out of scope? I've got multiple things that need to be destroyed, so how does the compiler choose the order? I could have two output possibilities:

parent c called           |         parent c called      
parent c called           |         parent c called
child c called            |         child c called
child d called            |         parent d called
parent d called           |         child d called
parent d called           |         parent d called

With the left case applying if Boy is destroyed first, and the right case applying if Man is destroyed first. How does the computer decide which one is deleted first?

Upvotes: 3

Views: 2561

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595537

A derived destructor is called before an ancestor destructor. So the Child destructor body will be called first, then the Parent destructor body next. And constructed objects are destructed in reverse order, so the Boy object will be destructed before the Man object is destructed.

Upvotes: 6

Related Questions