1

I've a simple problem but I really can't understand why. I think you can help me.

I have a template base class :

template <class T> class Base
{
    public:
        T foo(T t);
    protected:

        Base();
        ~Base();
};

I want to derive a specialisation of this template :

class Derived : public Base<std::string>
{
    public:
        Derived();
        virtual ~Derived();
};

All the functions are defined in the respective .cpp (they are empty, except for foo which just returns t)

I chose std::string as an example. But this simple code doesn't compile. I have errors : "indefinite reference to "Base::Base()" "indefinite reference to "Base::~Base()"

It seems that I follow examples on internet but it doesn't work... I really don't understand this one, it must be obvious!

Can you help me? :)

(PS : sorry if my english is bad)

2 Answers2

4

When you inherit from a class template, base class declaration and definition need to be in the header file.

The reason for this is that compiler needs to instantiate the template in compile time for the types you use, during compile time. Foreign Cpp files are only accessed during linkage, hence when compiler tries to instantiate derived class it cannot instantiate template code and the error you mentioned results.

aybassiouny
  • 559
  • 5
  • 14
0

This example compiles perfectly, so where is your problem?

#include <string>

template <class T> class Base
{
    public:
        T foo(T t) {};
    protected:
        Base() {};
        ~Base() {};
};

class Derived : public Base<std::string>
{
    public:
        Derived() {};
        virtual ~Derived() {};
};

int main()
{
    Derived derived;
    return 0;
}
Chiel
  • 6,006
  • 2
  • 32
  • 57
  • It seems that it is necessary to define the function inside the .h, and not the .cpp... Could you tell me why? – matthieu perez Apr 11 '16 at 10:03
  • See my other comment. If you use templates you have to put your implementation inside of the header, or you have to resort to other tricks. See http://stackoverflow.com/questions/1724036/splitting-templated-c-classes-into-hpp-cpp-files-is-it-possible – Chiel Apr 11 '16 at 10:04
  • It may compile but any function that calls `Base::foo()` and uses its return value will have undefined behaviour. – Peter Apr 11 '16 at 10:18