TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
C++ Coding Standard

Rule:  OLC#005Checked automatically with code checker

Synopsis:A virtual method may only be called if an object is fully constructed
Severity Level:1
Category:Object Life Cycle


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.


class B {
        B(const string& ss) { f(ss); }
        virtual void f(const string&) {}
    class D : public B {
        D(const string & ss) :B(ss) { }
        void f(const string& ss) { s = ss; }
        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.