Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!tut.cis.ohio-state.edu!unmvax!polyslo!ttwang From: ttwang@polyslo.CalPoly.EDU (Thomas Wang) Newsgroups: comp.lang.c++ Subject: Re: Constructors and new Message-ID: <11629@polyslo.CalPoly.EDU> Date: 3 Jun 89 16:15:24 GMT References: <363@msor0.UUCP> Reply-To: ttwang@polyslo.CalPoly.EDU (Thomas Wang) Distribution: usa Organization: Cal Poly State University -- San Luis Obispo Lines: 35 In article <363@msor0.UUCP> kt@msor.UUCP (Keith Tizzard) writes: >According to BS, section 5.5.7, a constructor for a class can determine whether >it was called by new or not. >"If it is called by new, the pointer this has the value zero at entry, >otherwise this points to space already allocated for the object..." >#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; } Testing (this == 0) only works if you set 'this' to some value inside the constructor. I have a non-portable hack though. testclass::testclass() { int dummy; if (this < &dummy) puts("Used new\n"); else puts("did not use new\n"); } This hack depends on the fact that stack and heap usually grows into each other from opposite side of memory. -Thomas Wang (Mak-Kuro Kurosuke, come on out! If you don't come out, we'll pull your eyeballs out! - as heard in Tonari No Totoro ) ttwang@polyslo.calpoly.edu