0

I am attempting to make a manual generic stack class that does some other things when pushing and popping, however when I compile it, I am getting undefined reference errors for every reference to the class that I use in main. I tested it first using int instead of T and everything worked fine, so it's the conversion to generic that is giving me the problems. Header:

template <typename T>
class Stack
{
public:
    Stack();
    void push(T item);
    T pop();
    int nbrOfItems() const;
    int capacity() const;
private:
    T* stack;
    int nbrItems;
    int size;
};

CPP:

#include "Stack.h"

template <typename T>
Stack<T>::Stack()
{
    size = 1;

    stack = new T[size]();

    nbrItems = 0;
}

template <typename T>
void Stack<T>::push(T item)
{
    //push things
}

template <typename T>
T Stack<T>::pop()
{
    //pop things

}

template <typename T>
int Stack<T>::nbrOfItems() const
{
    return nbrItems;
}

template <typename T>
int Stack<T>::capacity() const
{
    return size;
}
  • Your bug is having a cpp file – drescherjm Aug 02 '22 at 03:42
  • @drescherjm we were told to use a CPP file. if that's the only problem though, i'm going to cry – erica_on_strike Aug 02 '22 at 03:44
  • 1
    Move all the contents of the `.cpp` file into the header file and remove the `.cpp` file. Completely opposite to non-template functions, you need to implement (member) function templates inside the header. See linked duplicate. – user17732522 Aug 02 '22 at 03:44
  • 1
    @erica_on_strike That is correct for everything that is not a template. Definitions for non-template stuff must usually go into the `.cpp` file (definitions of classes and such aside). But for everything templated it is the other way around. They usually _cannot_ be implemented in a `.cpp`. – user17732522 Aug 02 '22 at 03:45

0 Answers0