0

While instantiating the class in main I am getting these two errors:

error LNK2019: unresolved external symbol "public: __thiscall templateClass<int>::templateClass<int>(void)" (??0?$templateClass@H@@QAE@XZ) referenced in function _wmain

error LNK2019: unresolved external symbol "public: __thiscall templateClass<int>::~templateClass<int>(void)" (??1?$templateClass@H@@QAE@XZ) referenced in function _wmain

Code

templateClass.h

#pragma once

#define MAX 10

template<class T>
class templateClass
{

private:
    T arr[MAX];
    int size;
public:
    templateClass(void);
    void initArrayWithZero();
    void pushElementIntoArray(T element );
    void printArray();
    ~templateClass(void);
};

templateclass.c

#include "templateClass.h"

template <class T>
templateClass<T>::templateClass(void)
{
    size = 0;
}

template <class T>
templateClass<T>::~templateClass(void)
{
}

template <class T>
void templateClass<T>::pushElementIntoArray(T element )
{
    if(size<MAX)
    {
        T[size++] = element;
    }
    else
    {
        //Give error code
    }
}

template <class T>
void templateClass<T>::initArrayWithZero()
{
    for(i= 0; i<MAX; i++)
        T[i] = 0;
}

template <class T>
void templateClass<T>::printArray()
{
    for( int i =0; i<MAX; i++)
        cout<<"\n"T[i];
}

Main.cpp

#include "stdafx.h"
#include "templateClass.h"

int _tmain(int argc, _TCHAR* argv[])
{
    templateClass<int> intarray;
    return 0;
}

How can I fix this?

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
Maddyfire
  • 61
  • 5

1 Answers1

1

Template classes such as templateClass<T> must (usually) be implemented in header (.h) files.

As such, you need to move the content of templateclass.c to templateClass.h and delete templateclass.c.

See Why can templates only be implemented in the header file? for more information.

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • But I am getting another error when I am trying to print the elements of array . error C2275: 'T' : illegal use of this type as an expression for( int i =0; i – Maddyfire Oct 13 '13 at 04:11
  • @Maddyfire: Happy to help. Your next problem is that `T` is the *type* and `arr` is the *variable*. You probably meant `for (int i = 0; i< MAX; i++) { std::cout << "\n" << arr[i]; }` (or similar). – johnsyweb Oct 13 '13 at 04:33