Search code examples
c++polymorphismvirtual-functionspure-virtual

Where do "pure virtual function call" crashes come from?


I sometimes notice programs that crash on my computer with the error: "pure virtual function call".

How do these programs even compile when an object cannot be created of an abstract class?


Solution

  • They can result if you try to make a virtual function call from a constructor or destructor. Since you can't make a virtual function call from a constructor or destructor (the derived class object hasn't been constructed or has already been destroyed), it calls the base class version, which in the case of a pure virtual function, doesn't exist.

    class Base
    {
    public:
        Base() { reallyDoIt(); }
        void reallyDoIt() { doIt(); } // DON'T DO THIS
        virtual void doIt() = 0;
    };
    
    class Derived : public Base
    {
        void doIt() {}
    };
    
    int main(void)
    {
        Derived d;  // This will cause "pure virtual function call" error
    }
    

    See also Raymond Chen's 2 articles on the subject