Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!uwvax!dave From: dave@spool.wisc.edu (Dave Cohrs) Newsgroups: comp.lang.c++ Subject: Re: Interesting "Feature" of C++ Message-ID: <4513@spool.wisc.edu> Date: Wed, 21-Oct-87 13:52:41 EDT Article-I.D.: spool.4513 Posted: Wed Oct 21 13:52:41 1987 Date-Received: Sat, 24-Oct-87 05:08:16 EDT References: <1718@dasys1.UUCP> Sender: news@spool.wisc.edu Reply-To: dave@spool.wisc.edu (Dave Cohrs) Organization: U of Wisconsin CS Dept Lines: 68 Keywords: virtual functions, assigning to this In article <1718@dasys1.UUCP> wfp@dasys1.UUCP (William Phillips) writes about a problem with changing "this" in a constructor. Sorry, but I don't have a solution, but I have an even more painful problem. If we take William's example and expand it a bit (I added a constructor to "base": >struct base { > . > . base(); // a constructor for base > base *something(); // defined elsewhere > base *something_else(); > virtual void whatever(); > . > . > . >} > >struct derived : base { > . > . > . > void whatever(); > . > . > . >} > derived* something(); > . > . > . > this = something(); > if (this == NULL) { > this = something_else(); > } > . > . > . > Now, when you reassign "this", the base constructor gets called to reinitialize the data. This is very harmful in two cases, if you set this to nil, or if you set this to an allready allocated and initialized object. In the first case, if you say "this = 0" (yes, explicit assignments are just as bad), or in any way set this to a nil pointer, base::base will reallocate space for this and this in "derived" will not be nil after the assignment. In the second case, say that you have a list of objects of type "derived". Have the derived constructor search the list until it finds an appropriate object, and then assigns this to that object. Once again, the base constructor is called, possibly destroying all useful data in the object. Actually, this behaviour is documented. See sec. 8.5.8 in the C++ book. Think of the virtual table pointer as a member (albeit invisible) of the object. Then, following the rules in 8.5.8, the table pointer gets set after reassigning "this". Note that I saw no code to check if this was set to nil in any case. Dave Cohrs Still single after all these years +1 608 262-6617 UW-Madison Computer Sciences Department dave@cs.wisc.edu ...!{harvard,ihnp4,rutgers,ucbvax}!uwvax!dave