Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!zephyr.ens.tek.com!tekcrl!brucec From: brucec@phoebus.phoebus.labs.tek.com (Bruce Cohen;;50-662;LP=A;) Newsgroups: comp.lang.c++ Subject: Re: Can a base class know which derived class is constructed? Message-ID: Date: 12 Sep 90 20:21:22 GMT References: Sender: news@tekcrl.LABS.TEK.COM Organization: Tektronix Inc. Lines: 74 In-reply-to: amehta@ptolemy1.rdrc.rpi.edu's message of 12 Sep 90 12:56:54 GMT In article amehta@ptolemy1.rdrc.rpi.edu writes: > > I have a base class, say BASE, and several derived classes. > Can the base class know which derived class is being created > at the time of construction? I want to avoid passing parameters > if possible. > Why? You can have the parameters passed automatically by the derived class' constructor, so the main program doesn't need to get involved. > I tried a virtual identity method, but the method becomes valid > only AFTER construction. Consider: > Yep, you can't do that because any virtual function call in a constructor is automatically converted to a call to the function in the constructor's class. This prevents accidentally calling the virtual of a class before the class' constructor has been run, i.e. before a valid object exists. Here's a way to do it with parameter passing and a data member in class BASE: #include class BASE { public: BASE (const char* ident = "BASE") { printf ("Cons: BASE\n"); identity = ident; identify(); } void identify () { printf ("Ident: I am a %s\n", identity); } protected: const char* identity; }; class DER1 : public BASE { public: DER1 (const char* ident = "DER1") : BASE(ident) { printf ("Cons: DER1\n"); identity = ident; identify(); } }; class DER2 : public DER1 { public: DER2 (const char* ident = "DER2") : DER1 (ident) { printf ("Cons: DER2\n"); identity = ident; identify(); } }; main() { printf ("Starting\n"); DER2 d; d.identify(); printf ("Done\n"); } /*-------- This program produces as output: ------- Starting Cons: BASE Ident: I am a DER2 Cons: DER1 Ident: I am a DER2 Cons: DER2 Ident: I am a DER2 Ident: I am a DER2 Done -- --------------------------------------------------------------------------- NOTE: USE THIS ADDRESS TO REPLY, REPLY-TO IN HEADER MAY BE BROKEN! Bruce Cohen, Computer Research Lab email: brucec@tekcrl.labs.tek.com Tektronix Laboratories, Tektronix, Inc. phone: (503)627-5241 M/S 50-662, P.O. Box 500, Beaverton, OR 97077