Sequence of constructor calls and destructor calls.

H

Honne Gowda A

Hi,
Can anybody clarify why destruction happens in reverse way?
for example A<-B<-C, when C's object is constructed, ctor calls will A(),B() and
C(), when this object is destroyed, sequence of calls will be ~C(),~B(),and
~C(). I am wondering why cant' we destroy the object like ctor way?..Are there
any good reasons for this?

thanks,
-Honne
--
 
J

Josephine Schafer

Honne Gowda A said:
Hi,
Can anybody clarify why destruction happens in reverse way?
for example A<-B<-C, when C's object is constructed, ctor calls will A(),B() and
C(), when this object is destroyed, sequence of calls will be ~C(),~B(),and
~C(). I am wondering why cant' we destroy the object like ctor way?..Are there
any good reasons for this?

Logically if you agree that before becoming a C object it first becomes an A,
then B and *then* a C object.
(Constructor call sequence)
Then you should also agree that when it has to destruct it should first become B
from C, and then A from B and then nothing!

If I were to make a pile of books I would build it one over another. But when I
were to remove it I would go the other way from top to bottom, unless I want the
whole pile to fall down :)

HTH,
J.Schafer
 
K

Karl Heinz Buchegger

Honne said:
Hi,
Can anybody clarify why destruction happens in reverse way?
for example A<-B<-C, when C's object is constructed, ctor calls will A(),B() and
C(), when this object is destroyed, sequence of calls will be ~C(),~B(),and
~C().

You mean ~A() :)
I am wondering why cant' we destroy the object like ctor way?..Are there
any good reasons for this?

Generally it is most always a good idea to undo things in the exact reverese
order that they got done.

But in specific:
Suppose class C is dependent on things in A. For the construction this
is not a problem, since C is constructed after A has finished construction,
so at the time the ctor of C runs, it can access all of A's functionality.

But then destructin happens. Again C has to do work and wants to use information
from A. If A gets destructed first, then that information will not be available
any more. But if the destruction starts at C it can use everything from A needed
to do its job.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top