Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!decwrl!sun-barr!apple!bbn!rochester!pt.cs.cmu.edu!pt!dld From: dld@F.GP.CS.CMU.EDU (David Detlefs) Newsgroups: comp.lang.c++ Subject: Re: Constructors and new Message-ID: Date: 31 May 89 14:40:58 GMT References: <2684@ssc-vax.UUCP> Organization: CMU CS Department Lines: 45 In-reply-to: dmg@ssc-vax.UUCP's message of 30 May 89 22:10:40 GMT Dave Geary asks why this program: #include >class testclass >{ > public: > > testclass() { if(this == 0) puts("Used new..."); else puts("Did not use new..."); } > ~testclass() { puts("I'm a destructor..."); } >}; > >main() >{ > testclass var; > new testclass; >} produces this output: >Did not use new... >Did not use new... >I'm a destructor... I believe I can explain this. Look at 'main.' The first line of the output is caused by the constructor call to initialize 'var', a stack-allocated automatic variable. The second line is caused by the evaluation of the expression 'new testclass;' This *does* use new, so why does it say it doesn't? Well if you look at testclass, you'll find that sizeof(testclass) is 0. I would guess that the 'malloc' that operator new is calling returns 0 when it is asked to allocate a zero-sized object. Thus, 'this' is 0 on entry to the constructor. Finally, the testclass destructor is called when 'var' goes out of scope. Hope this helps. Dave -- Dave Detlefs Any correlation between my employer's opinion Carnegie-Mellon CS and my own is statistical rather than causal, dld@cs.cmu.edu except in those cases where I have helped to form my employer's opinion. (Null disclaimer.) --