Synopsis: | A virtual method may only be called if an object is fully constructed |
Language: | C++ |
Severity Level: | 1 |
Category: | Object Life Cycle |
Description: |
A method is made virtual so that derived classes can override it. A derived class overrides a method so that its method, rather than that of its base class is executed. This does not work when a virtual method is called from for instance the constructor or destructor of a base class. In those cases, the method of the base class is called. In case the base class method is pure virtual it will even lead to an exception. Example: class B { public: B(const string& ss) { f(ss); } virtual void f(const string&) {} }; class D : public B { public: D(const string & ss) :B(ss) { } void f(const string& ss) { s = ss; } private: string s; }; int main() { D d("Hello"); } In the main function an object of type D is created. This is done by the constructor of class D. This constructor calls the constructor of its parent B in the initializer list. The parent constructor calls in its body the function f, which is virtual and overriden in class D. So one would expect that the f that is called in constructor B is the function f that is defined in class D. But this is not happening, the compiler willl call the function f that is defined in class B. In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn’t yet happened. |