Search code examples
c++c++11pure-virtual

C++ LNK2001 Error When declaring Pure Virtual Function


I have two classes, base class A and derived class B. Definition as below:

Class A {
public:
    A()
    {
        ImpleDefinition();
    }
    ~A()=default:

protected:
    virtual void ImplDefinition()=0;
}

class B : public A
{
public:
    B() : A()
    {
    }
    ~B()=default;

private:
    void ImplDefinition() override
    {
        /*Some detailed implementation*/
    }
}

So when compiling this code, compiler reports "error LNK2001: unresolved external symbol" error. From code itself, I can't see I made any mistake. Interesting, if I change "ImplDefinition" from pure virtual function to virtual function.

void ImplDefinition() {};

Then everything works fine. How to explain this situation?


Solution

  • The problem is you're calling the virtual function ImplDefinition() in A::A(). When in the constructor of the base class, the current object is always the base class subobject, the derived class part is not constructed at all; which will be performed later. Then the pure virtual A::ImplDefinition() will be called and cause the error; no dynamic dispatch here, B::ImplDefinition() won't be called at all.

    Further reading about When my base class’s constructor calls a virtual function on its this object, why doesn’t my derived class’s override of that virtual function get invoked?