Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cornell!uw-beaver!mit-eddie!rutgers!att!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: Virtual functions in constructors Message-ID: <9127@alice.UUCP> Date: 1 Apr 89 00:21:30 GMT References: <1129@internal.Apple.COM> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 67 In article <1129@internal.Apple.COM>, arn@apple.com (Arn Schaeffer) writes: > Option #1: > Do not allow virtual function calls in constructors. > Option #2: > Because base classes are initialized before derived classes, a virtual > function appearing in the constructor of a base class should call the > virtual function as it was defined for the base class. > Option #3: > Virtual functions always invoke the definition in the derived class. Option 2 is correct. Imagine a base class B and a class D derived from B. Constructing a D object involves first constructing the B that is part of it. If a virtual function in B were called by B::B(), and it were to a member of D, that would be executing a member of D before initializing the D object. Because D::D() can control which particular constructor of B gets called, it is possible to make B behave differently when constructed as part of a D than when constructed independently. It is even possible to protect it: class B { public: B(); protected: B(int); // and so on }; class D: public B { public: D(int n): (n) { /* stuff */ } // and so on }; The (n) in the definition of D::D(int) is the argument to be handed to the base class (B). Because B::B(int) is protected, it is impossible to create a B object directly from an int (although bugs in some C++ implementations may let it slip by anyway). Incidentally, option 1 is practically impossible to enforce: class B: extern void fudge(B*); class B { public: B() { fudge(this); } // and so on }; If fudge() is separately compiled, how can the compiler know that it should not call any virtual functions? -- --Andrew Koenig ark@europa.att.com