Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!zaphod.mps.ohio-state.edu!sdd.hp.com!decwrl!sgi!shinobu!odin!rome.wpd.sgi.com!jfw From: jfw@rome.wpd.sgi.com (john fergus wilkinson) Newsgroups: comp.lang.c++ Subject: Re: problem with virtual function Message-ID: <1990Aug21.002654.20506@odin.corp.sgi.com> Date: 21 Aug 90 00:26:54 GMT References: <9008201757.AA23899@sirius.risc.com> Sender: news@odin.corp.sgi.com (Net News) Reply-To: jfw@rome.wpd.sgi.com (john fergus wilkinson) Organization: Silicon Graphics, Inc., Mountain View, CA. Lines: 35 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; > } See Ellis and Stroustrup, Section 12.7.