Path: utzoo!utgpu!watserv1!watmath!att!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: constructor called within constructor??? Message-ID: <11017@alice.UUCP> Date: 5 Jul 90 15:00:50 GMT References: <965@unet.UUCP> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 62 In article <965@unet.UUCP>, noemi@sugarfoot.net.com (Me) writes: > I'm trying to call a constructor routine (1) from withing another > constructor routine (2). Essentially, I want constructor 2 to do > exactly what constructor 1 does, plus one extra thing: > > public: > classname(); /* constructor 1 */ > classname(int arg); /* constructor 2 */ > /* constructor 1 */ > classname:classname() > { > /* lots of things */ > } > /* constructor 2 */ > classname:classname(int arg) > { > classname(); /* call constructor 1 */ > privatevar = arg; /* "one extra thing" */ > } Of course this doesn't work: the call classname(); means `please construct an object of type `classname' using its empty constructor and then throw it away.' In fact, there is no way to call a constructor explicitly (yes, I know this statement is not completely true, but it is true for this purpose); the way to do what you want is to reorganize your program slightly: public: classname(); // constructor 1 classname(int); // constructor 2 private: void build(); // do the real work classname::classname() // constructor1 { build(); } classname::classname(int arg) // constructor2 { build(); privatevar = arg; } void classname::build() { // the stuff that was in constructor1 } If you're worried about overhead, make the `build' function inline. -- --Andrew Koenig ark@europa.att.com