0

I'm trying to create a template c++ Stack, and i'm having some issue with the linker. I've tried to put all the classes into one cpp file, and it works just fine, but the problem begin once I separate them into different files here's my classes

main class :

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

using namespace std;

int main()
{
    Stack<double>* st = new Stack<double>();
    st->push(new Data<double>(10));

    cout << st->pop()->getData();

    return 0;
}

stack.h :

#ifndef STACK_H
#define STACK_H

#include "data.h"

template <class T>
class Stack
{
public:
    Stack():_current(NULL){}
    void push(Data<T>* const);
    Data<T>* pop(); 

private:
    Data<T>* _current;
};

#endif;

stack.cpp :

#include "stack.h"

template <class T>
Data<T>* Stack<T>::pop()
{
    if(this->_current == NULL)
    {
        cout << "Empty stack." <<endl;
        return NULL;
    }
    else
    {
        Data<T>* tmpPtr = this->_current;
        this->_current = this->_current->getPrev();
        return tmpPtr;
    }
}

template <class T>
void Stack<T>::push(Data<T>* const data)
{
    if(this->_current == NULL) // Empty stack;
    {
        _current = data;
        _current->setPrv(NULL);
    }
    else
    {
        Data<T>* tmpPtr = this->_current;
        this->_current = data;
        this->_current->setPrv(tmpPtr);
    }
}

data.h

#ifndef DATA_H
#define DATA_H

template <class T>
class Data
{
public:
    Data(T data):_data(data){}
    T getData() const { return this->_data; }
    void setPrv(Data* const prev){ this->_prev = prev; }
    Data* getPrev() const { return this->_prev; }
private:
    Data<T>* _prev;
    T _data;
};

#endif
Wagdi Kala
  • 63
  • 5

2 Answers2

1

Put all the definitions of the template class functions in the .h. They basically aren't allowed to be in separate files.

This occurs becauses templates are not like typical classes. The compiler will generate a class for you off of your template instantiation. Because of this, the compiler will need to know where to lookup the function definitions, so put them inside the .h where the class is defined.

pippin1289
  • 4,861
  • 2
  • 22
  • 37
1

Template functions are not compiled until they're specialized(used), and your stack.cpp doesn't produce any machine code. Move them to stack.h

jaeheung
  • 1,208
  • 6
  • 7