Within an application I am presently writing, I produced a template class having a pure virtual function, then an another class getting a clear case of the previous and applying the virtual function. The virtual function is known as in the parent's constructor, which is often used through the child also. I can not build this code because of linker errors and that i can't understand why. Here is a simplified version from the code to breed the problem I am getting.

template <typename T> class Foo
{
public:
    Foo(T a)
    {
        x = a;
        echo();
    }

protected:
    T x;
    virtual void echo() = 0;
};

class Bar : public Foo<int>
{
public:
    Bar(int a) : Foo<int>(a)
    {
    }

    void echo();
};

void Bar::echo()
{
    cout << "value: " << x << endl;
}

int main(int argc, char* argv[])
{
    Bar bar(100);
    return 0;
}

The linker error seems the following in MSVC:

purevirttest.obj : error LNK2019: conflicting exterior symbol "protected: virtual void __thiscall Foo::echo(void)" (?echo@?$Foo@H@@MAEXXZ) recommended in function "public: __thiscall Foo::Foo(int)" (???$Foo@H@@QAE@H@Z)

Basically slowly move the call to echo() from Foo's constructor, the code develops and executes nicely, I'm able to call bar.echo() with no problems. Issue is I'd enjoy that function within the constructor. Any explanation of the mystery higly appreciated.

You cannot call echo() in the constructor of Foo<T>.

Within the constructor of Foo<T>, the dynamic kind of the item is Foo<T>. It isn't until following the Foo<T> constructor finishes the dynamic type becomes Bar.

Since echo() is pure virtual in Foo<T> and also, since Foo<T> may be the dynamic kind of the item, you can't call echo() within the constructor of Foo<T>.

Unless of course you're very acquainted with the way the dynamic kind of an item changes throughout construction and destruction, it might be advisable to not try calling virtual functions from constructors and destructors.