0

Possible Duplicate:
Why can templates only be implemented in the header file?
Undefined symbol on a template operator overloading function

For my school assignment, I need to make a program that makes a stack using a linked list. I keep getting linker errors though (specifically: error LNK2019: unresolved external symbol "public: __thiscall Stack::Stack(void)" (??0?$Stack@H@@QAE@XZ) referenced in function _main 1>C:\Users\devon.taylor\Desktop\New folder\Debug\PA3.exe : fatal error LNK1120: 1 unresolved externals)

Here is my code:

Header:

template <class T>
class  Stack
{
public:
    Stack();
    Stack(T data);
    ~Stack();
    void push(T data);
    T pop();
    void display();
    bool isEmpty();
    bool isExist(T searchKey);

private:
    Stack<T> *top;
    Stack<T> *next;
    T mData;
};

Functions:

#include "stack.h"
#include <iostream>

using namespace std;

template <class T>
Stack<T>::Stack()
{
    top=NULL;
}

template <class T>
Stack<T>::Stack(T data)
{
    mData = data;
    pNext = NULL;
}

template <class T>
Stack<T>::~Stack()
{

}

template <class T>
void Stack<T>::push(T data)
{
   Stack *ptr;
   ptr=new Stack<T>;
   ptr->mData=data;
   ptr->next=NULL;

   if(top!=NULL)
   {
      ptr->next=top;
   }
   top=ptr;
   cout<<"\nNew item inserted to the stack";
}        

template <class T>
T Stack<T>::pop()
{


}
template <class T>
void Stack<T>::display()
{

}

Main Function:

#include <iostream>
#include "stack.h"

using namespace std;

void main ()
{
    Stack<int>* stack;
    stack = new Stack<int>;
    //stack->push(19);



    system("pause");
}
Community
  • 1
  • 1
nym_kalahi
  • 91
  • 1
  • 2
  • 9

1 Answers1

2

You must implment template functions in the header file for the linker to pick it up. See this question for more details.

Also, look at the C++ FAQ for more details.

Community
  • 1
  • 1
xxbbcc
  • 16,930
  • 5
  • 50
  • 83
  • Could you please explain what you mean? – nym_kalahi Sep 25 '12 at 22:22
  • See also this FAQ: [How can I avoid linker errors with my template classes?](http://www.parashift.com/c++-faq/separate-template-class-defn-from-decl.html) – ildjarn Sep 25 '12 at 22:22
  • @user1698667 I updated my answer with extra links - please read those. You'll be better off with those detailed explanations than with me trying to write up a complete answer for you. :) – xxbbcc Sep 25 '12 at 22:28