Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!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: problem with virtual function Message-ID: Date: 20 Aug 90 19:48:50 GMT References: <9008201757.AA23899@sirius.risc.com> Sender: news@tekcrl.LABS.TEK.COM Organization: Tektronix Inc. Lines: 74 In-reply-to: ckl@SIRIUS.RISC.COM's message of 20 Aug 90 17:57:21 GMT In article <9008201757.AA23899@sirius.risc.com> ckl@SIRIUS.RISC.COM (Carl K. Lim) writes: > > > Hello. I have this problem: when I'm calling a virtual function from a parent > class's constructor, it fails to execute the derived class's function. For > example, in the following program, when B is declared, print() is called from > A's constructor. But instead of looking up the B::print(), A::print() is > called instead. Has anybody run into this kind of problem? Is there a way > to get around it? > > #include > > class A > { > public: > A() { print(); } > virtual void print() { printf("A\n"); } > }; > > > class B : public A > { > public: > B() {} > void print() { printf("B\n"); } > }; > > > int main() > { > B b; > } What you are seeing is the way the language is specified to work: overloading of a virtual function is ignored when the function is called from a constructor. From the bible (Ellis & Stroustrup, "The Annotated C++ Reference Manual") page 294, scectio 12.7: "Member functions may be called in constructors and destructors. This implies that virtual functions may be called (directly or indirectly). The function called will be the oned defined in the constructor's (or destructor's) own class or its bases, but *not* [italics theirs] any functions overriding it in a derived class. This ensures that unconstructed objects will not be accessed during construction and destruction." That insurance is necessary because constructors are called in order from the base class out towards the derived class. To get the effect I think you want, put a print(); statement in B's constructor: class B : public A { public: B() { print(); } void print() { printf("B\n"); } }; If that's not good enough, then you'll have to change your main to: int main() { B b; b->print(); } -- --------------------------------------------------------------------------- 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