From: Erik Max Francis Newsgroups: comp.os.msdos.djgpp,gnu.gcc.help,comp.os.os2.programmer.misc Subject: Re: C++ constructor problem solved!! Read how, it might come in useful in your future programs! Date: Sun, 18 Jan 1998 14:26:02 -0800 Organization: Alcyone Systems Lines: 56 Message-ID: <34C2817A.5547BE86@alcyone.com> References: NNTP-Posting-Host: newton.alcyone.com Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk Gili wrote: > However, we wanted to be able to call the base constructor > from the > body of the File() constructor. This would allow more flexibility, > mainly allowing you to use exception-handling for this call. The > solution took me 2 days to find, but here it is: > > File::File() > { > ((fstream*)this)->fstream(); > > } Explicitly calling constructors is dangerous. Here what's _really_ happening is that the fstream is being constructed with the default constructor, and _then_ you're explicitly calling a nondefault constructor. That is, it's functionally precisely the same thing as: File::File(...): fstream() { ((fstream *) this)->fstream(...); ... } This is unwise and can have unwanted side effects, particularly if memory is being allocated in the default constructor (because then it will get allocated twice). The proper (meaning, standard and safe) way to do what you want is to have a pointer to an fstream contained within the class, and then create that dynamically when needed: class File { public: fstream *fs; File(...); ... }; File::File(...) { fs = new fstream(...); ... } -- Erik Max Francis, &tSftDotIotE / mailto:max AT alcyone DOT com Alcyone Systems / http://www.alcyone.com/max/ San Jose, California, United States / icbm://+37.20.07/-121.53.38 \ "Life may be / the product of imperfections." / (Marclo Gleiser)