0

Possible Duplicate:
Undefined reference error for template method

Hello I have this code that is giving me this error:

undefined reference to `MyStack::push(int)' main.cpp

Why??

MyStack.h:

#ifndef STACK_H
#define STACK_H

template <typename T>
class MyStack
{
private:
    T *stack_array;
    int count;

public:
    void push(T x);
    void pop(T x);

    void xd(){}
};

#endif /* STACK_H */

MyStack.cpp:

#include "mystack.h"

template <typename T>
void MyStack<T>::push(T x)
{
    T *temp;
    temp = new T[count];

    for(int i=0; i<count; i++)
        temp[i] = stack_array[i];

    count++;

    delete stack_array;
    stack_array = new T[count];

    for(int i=0; i<count-1; i++)
        stack_array[i] = temp[i];
    stack_array[count-1] = x;
}

template <typename T>
void MyStack<T>::pop(T x)
{

}

main.cpp:

#include <iostream>

#include "mystack.h"

using namespace std;

int main(int argc, char *argv[])
{
    MyStack<int> s;
    s.push(1);
    return 0;
}
Community
  • 1
  • 1
petermlm
  • 930
  • 4
  • 12
  • 27
  • 1
    As an aside, you will also need to initialise your count variable before using it probably in a constructor. – Drew Goodwin Apr 27 '11 at 09:16
  • Thanks!!! I did notice the need to initialize, but I wanted to solve this problem really bad because it was getting on my nerve, lol. – petermlm Apr 27 '11 at 12:49

3 Answers3

3

The definition of the members of the class template must be in the same file, but you've defined them in a different file (MyStack.cpp).

The simple solution is that add the following line to your MyStack.h file at the end:

#include "MyStack.cpp" // at the end of the file

I know that is .cpp file, but that will solve your problem.

That is, your MyStack.h should look like this:

#ifndef STACK_H
#define STACK_H

template <typename T>
class MyStack
{
private:
    T *stack_array;
    int count;

public:
    void push(T x);
    void pop(T x);

    void xd(){}
};

#include "MyStack.cpp" // at the end of the file

#endif /* STACK_H */

If you do so, then #include "mystack.h" is not needed in MyStack.cpp anymore. You can remove that.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
3

See C++ FAQ-35.12

dubnde
  • 4,359
  • 9
  • 43
  • 63
2

You have to place your template class declaration and implementation inside header file because compiler needs to know about template implementation when instantiating template while compiling. Try to put implementation of MyStack inside MyStack.h

You can find more detailed explanation here. Just move to the "Templates and multiple-file projects" at the bootom of the article.

beduin
  • 7,943
  • 3
  • 27
  • 24