Where do “pure virtual function call” crashes come from?

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.

(See live demo here)

class Base
{
public:
    Base() { doIt(); }  // DON'T DO THIS
    virtual void doIt() = 0;
};

void Base::doIt()
{
    std::cout<<"Is it fine to call pure virtual function from constructor?";
}

class Derived : public Base
{
    void doIt() {}
};

int main(void)
{
    Derived d;  // This will cause "pure virtual function call" error
}

Leave a Comment