Linker error

In my main function located in its separate file, I have the following call:
1
2
3
4
5
#include "Heap.h"
int main(){
Heap<int> myHeap;
myHeap.heapInsert(9);
}


In my header file I have:
1
2
3
4
5
6
7
8
9
template <typename T>
class Heap
{
public:
   Heap();  /** Default constructor. */
   // copy constructor is supplied by the compiler
   virtual ~Heap(); 
...
}


And in my .cpp file I have:
1
2
3
4
5
6
7
8
9
10
11
#include "Heap.h"  // header file for class Heap

template <typename T>
Heap<T>::Heap() : size(0)
{
}  // end default constructor

template <typename T>
Heap<T>::~Heap()
{
}  // end destructor 


But I keep getting 3 linker errors:


Error 11 error LNK2019: unresolved external symbol "public: __thiscall Heap<int>::Heap<int>(void)" (??0?$Heap@H@@QAE@XZ) referenced in function _main C:\Users\aaa\Documents\Visual Studio 2010\Projects\Heap\HeapTester.obj Heap

and
Error 9 error LNK2019: unresolved external symbol "public: virtual __thiscall Heap<int>::~Heap<int>(void)" (??1?$Heap@H@@UAE@XZ) referenced in function _main C:\Users\aaa\Documents\Visual Studio 2010\Projects\Heap\HeapTester.obj Heap

and

a similar error message to do with another function in the same project.

Why am I getting these?
Last edited on
The compiler has to see definitions of template functions that it could instantiate them.
Last edited on
Putting templated class methods in a .cpp file is something of a compiler-specific black art.

All your "Heap.cpp" stuff should be in "Heap.h". Template classes are not designed to go in .cpp files.

Read more here
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.14
When you use templates, you have to include the methods that use templates in your header files. This is called the inclusion model. Other alternatives are the decleration model and the separation model, but they're not so easy to implement.
Alright, thanks for the replies. I think I learned somewhere down the line that in order to make this work, I should include my .cpp file at the bottom of my .h file. Would this work? I just tried it and it generates new errors in my .cpp file which I'm not sure about. What possible errors could using this strategy cause?
Don't #include cpp files. Just cut and paste the stuff from your Heap.cpp file into your Heap.h file, and delete Heap.cpp.

Any errors you get after that are syntax errors you will need to fix.
Topic archived. No new replies allowed.