0

I am writing some code using template,but i got some link errors:

[Linker error] undefined reference to `Vector::Vector(Vector const&)'

But i wrote this function in a .cpp.Here is the code.

template <class T>

Vector<T>::Vector(Vector const& r)
{


m_nSize = r.size();
int i = 0;
m_pElements = new T[m_nSize];
    while(i <= m_nSize)
{
    m_pElements[i] = r[i];
    i++;
}
}

and it is declared here in .h:

template <class T>

class Vector
{

public:

Vector():m_nSize(0){ m_pElements = (T*)NULL; }
Vector(int size):m_nSize(size){ m_pElements = new T[size]; }
Vector(const Vector& r);
virtual ~Vector(){ delete m_pElements; }
T& operator[](int index){ return m_pElements[index];}
int size(){return m_nSize;}
int inflate(int addSize);
private:

    T *m_pElements;
    int m_nSize;
};

I'm really confused now...What should i do to correct is?

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • 2
    Related question: [Why can templates only be implemented in the header file?](http://stackoverflow.com/q/495021/20984) – Luc Touraille May 25 '12 at 08:38

2 Answers2

3

You should make implementations visible. Move

template <class T>
Vector<T>::Vector(Vector const& r)
{
    //....
}

from the cpp file to the header.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

See the C++ faq (http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13). Basically place the code in the header file.

sashang
  • 11,704
  • 6
  • 44
  • 58