www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/02/09/21:19:43

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Calling Class Constructors and Destructors
Date: Mon, 09 Feb 1998 18:51:09 -0500
Organization: Two pounds of chaos and a pinch of salt.
Lines: 58
Message-ID: <34DF966D.BEB@cs.com>
References: <34df6b1d DOT 3108479 AT news DOT easynet DOT co DOT uk>
NNTP-Posting-Host: ppp212.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Geoffrey French wrote:
> 
> I have a bit of a strange problem with DJGPP :
> 
 [snip class definition]
> 
> int main()
> {
>         TC x, *y;
> 
>         x = TC(1);
>         y = new TC(1);
> }
> 
> I find that upon calling the constructor TC(long i) in the line 'x =
> TC(1)' not only is the constructor called, but the destructor is
> called straight afterwards (!), thus deleteing the reserved memory for
> the variable a. However, in the line 'y = new TC(1)' only the
> constructor is called. It seems that whenever you say 'c =
> TClass(...)' the TClass destructor is called as well as the
> constructor.
> 
> Can anyone help?

Of course.  This is standard C++ stuff here and is not strictly relevant
to DJGPP, but I'm learning C++ as well and this topic just recently came
up in class.  The line "x = TC(1);" is broken down by the compiler into
three parts:

First, it creates a temporary unnamed object of type TC, and calls the
constructor with a value of 1.  The scope of this object is the
statement in which it occurs.  The object can be treated more or less
like a numeric constant:  more because it has no existence outside the
statement, but less because, unlike a numeric constant, the program
actually creates it at runtime.

Second, it assigns the temporary unnamed object to x using the default
copy constructor.

Third, the temporary unnamed object is now out of scope, so its
destructor is called.  Since x contains a bit-for-bit copy of the data
in this object, x's data is invalidated as a result.

The solution to this problem is to overload the '=' operator for class
TC to allocate new memory instead of simply copying the pointer.

The reason the second statement works is that objects allocated with new
are not destroyed until delete is called.

Hope this helps!

-- 
---------------------------------------------------------------------
|      John M. Aldrich       | "Always listen to experts.  They'll  |
|       aka Fighteer I       | tell you what can't be done, and why.|
|   mailto:fighteer AT cs DOT com   | Then do it."                         |
| http://www.cs.com/fighteer/|                - Lazarus Long        |
---------------------------------------------------------------------

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019