TITLE: calling the most virtual method during construction (Newsgroups: comp.std.c++, 6 Mar 98) ODLE: Kirk Odle > > [snip] I agree > > wholeheartedly that the practice of calling virtual functions from > > constructors is a likely source of "bugs" or unexpected program > > behavior. TREGAN: Loic Tregan > As the author of the original message, I remember the need for > virtual calls in ctor : > class A { > private : > int _x; > public > A(int x) { SetX(x) }; > virtual int GetX(); > virtual void SetX( int x ); > } > > class B : public A { > B() {.. } > virtual SetX( int x ); > } KANZE: jkanze@otelo.ibmmail.com This particular case is actually easily handled by means of a helper class, e.g.: class AHelper ; class A ; class A { public: A( AHelper const& initialValue ) ; virtual ~A() ; virtual setX( int x ) const = 0 ; virtual getX() = 0 ; } ; class AHelper { friend class A ; public: AHelper( int x ) ; ~AHelper() ; private: int myValue ; A* myOwner ; } ; A::A( AHelper const& initialValue ) , myX( 0 ) { initialValue.myOwner = this ; } AHelper::AHelper( int x ) : myValue( x ) , myOwner( NULL ) { } AHelper::~AHelper() { if ( myOwner != NULL ) myOwner->setX( myValue ) ; } The int passed as argument automatically converts to a temporary AHelper, whose destructor is called at the end of the full expression, i.e. when the constructor of A, and of all its derived classes, has finished running, and the object has its final type. Obviously, the derived classes must declare an appropriate constructor, and pass the object down. This isn't a general solution, of course, but it may be useful specific cases like the above.