From: "John Bodfish" Newsgroups: comp.os.msdos.djgpp Subject: Re: C++ question. (fwd) Date: 16 Jun 1997 21:55:51 GMT Organization: Ameritech Library Services Lines: 52 Message-ID: <01bc7a9f$b7225300$dfcde7c0@JOHNB.als.ameritech.com> References: NNTP-Posting-Host: n5223.als.ameritech.com To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk Andrew Deren wrote in article ... [extraneous stuff snipped throughout] > > my question is: > > will the constructor generate a new copy of this object each time I call > > it. > > And if it does will the memory previously taken by my_obj be freed? > my_obj Object; This needs to be changed to "Object my_obj;" This will result in the allocation of storage for an instance of the class "Object" named "my_obj". It will also cause the invocation of the default constructor (the one that takes no parameters) for objects of the Object class. This constructor will get called before the "main()" function is entered. > void InitObj(int x, int y) > { > my_obj = Object(x, y); This line will cause the invocation of the constructor for the "Object" class that takes two intergers as parameters; it will construct an anonymous instance of the "Object" class. This anonymous instance is then the parameter for the assignment operator that is called to assign its value to the my_obj instance of the Object class. The memory previously taken by my_obj won't be freed when this assignment operator executes. And sooner or later you'll come to grief on that very fact. Probably sooner, because you'll add a "pointer-to-thingy" member to your "Object" class and call "new" or "malloc" to allocate some memory and then wonder why every call to InitObj() seems to loose some memory. The answer is: default assignment operators do memberwise assignment, which means that your "pointer-to-thingy" member gets assigned the value WITHOUT THE PREVIOUS value getting "delete" or "free()" called for it. If you want to know more about this, get a good C++ introductory book. > } This (the end-of-function brace for the InitObj() function) will cause the destructor for the "Object" class to get called for the anonymous instance of "Object" created above. -- John Bodfish bodfish AT als DOT ameritech DOT com