Connecting Tech Pros Worldwide Forums | Help | Site Map

Sequence of constructor calls and destructor calls.

Honne Gowda A
Guest
 
Posts: n/a
#1: Jul 19 '05
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
--

Josephine Schafer
Guest
 
Posts: n/a
#2: Jul 19 '05

re: Sequence of constructor calls and destructor calls.



"Honne Gowda A" <honne@lucent.com> wrote in message
news:3FA21986.74BFC2DF@lucent.com...[color=blue]
> 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()[/color]
and[color=blue]
> 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?[/color]

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


Karl Heinz Buchegger
Guest
 
Posts: n/a
#3: Jul 19 '05

re: Sequence of constructor calls and destructor calls.




Honne Gowda A wrote:[color=blue]
>
> 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().[/color]

You mean ~A() :-)
[color=blue]
> I am wondering why cant' we destroy the object like ctor way?..Are there
> any good reasons for this?
>[/color]

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.

--
Karl Heinz Buchegger
kbuchegg@gascad.at
Closed Thread