3 Replies - 204 Views - Last Post: 21 January 2011 - 07:05 AM Rate Topic: -----

#1 bnc  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 103
  • Joined: 18-March 10

error getting in templates

Posted 21 January 2011 - 06:05 AM

I have included all the header file declartions correctly. But still I am getting errors...

header file:test.h
#include <iostream>

template <class T>
class MyVec
{
public:
        MyVec();
        ~MyVec();
private:
        T* array;
};




source file:test.cpp
#include "test.h"

template <class T>
MyVec<T>::MyVec()
{
        array = NULL;
}

template<class T>
MyVec<T>::~MyVec()
{
        if(array != NULL)
        {
                delete[] array;
                array = NULL;
        }
}




main file:
#include "test.h"

int main(void)
{
        MyVec<int> veci;
        return 0;
}



output:
/tmp/ccQfYS4M.o: In function `main':
main.cpp:(.text+0x8b): undefined reference to `MyVec<int>::MyVec()'
main.cpp:(.text+0x9b): undefined reference to `MyVec<int>::~MyVec()'
collect2: ld returned 1 exit status

This post has been edited by bnc: 21 January 2011 - 06:11 AM


Is This A Good Question/Topic? 0
  • +

Replies To: error getting in templates

#2 Munawwar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 161
  • View blog
  • Posts: 457
  • Joined: 20-January 10

Re: error getting in templates

Posted 21 January 2011 - 06:32 AM

For template classes, the definition and declaration should be in the same file. Read this and the reason as to why things work this way.

This post has been edited by Munawwar: 21 January 2011 - 06:33 AM

Was This Post Helpful? 3
  • +
  • -

#3 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5676
  • View blog
  • Posts: 22,538
  • Joined: 23-August 08

Re: error getting in templates

Posted 21 January 2011 - 06:33 AM

You should implement the functions inside the .h file for templates.
Was This Post Helpful? 1
  • +
  • -

#4 bnc  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 103
  • Joined: 18-March 10

Re: error getting in templates

Posted 21 January 2011 - 07:05 AM

thanks Munawwar and JackOfAllTrades...

This post has been edited by bnc: 21 January 2011 - 07:06 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1