0

Possible Duplicate:
Why can templates only be implemented in the header file?

When I include MyClass.h and do:

MyClass<int, int> ccc = MyClass<int, int>();
ccc.myMethod1(3, 4);

I get a lot of errors telling undefined reference to constructor and methods ... However when I include MyClass.cpp (which is not a proper why to code) there is no error ! How to fix that ?

I'm compiling under Code::Blocks using g++

Community
  • 1
  • 1
shn
  • 5,116
  • 9
  • 34
  • 62
  • 1
    See [Why can templates only be implemented in the header file?](http://stackoverflow.com/q/495021/20984). – Luc Touraille Jan 25 '12 at 10:40
  • maybe you intended at line 1 **MyClass ccc;** – CapelliC Jan 25 '12 at 10:43
  • @chac is there any difference between **MyClass ccc;** and **MyClass ccc = MyClass();** ? It's like **vector v;** and **vector v = vector();** it's the same thing I think. – shn Jan 25 '12 at 11:28

1 Answers1

2

The reason is that template classes are not compiled, only instantiated templates will be compiled.

Rule of thumb: don't place template implementations in a cpp file but either directly in the header or another file included by the header (if you want to part implementation from the interface).

E.g:

myclass.h

template<typename A>
class MyClass
{
    ...
};

#include "myclass.inc"

myclass.inc

//implementation goes here: 
....
Constantinius
  • 34,183
  • 8
  • 77
  • 85