0

Stack is a template class with a vector m_elem. Vector type is also template. So in main I am trying to push an int into the vector but it is showing undefined reference. No idea y is this happening. The program is as follows.

main file

int main()
{   
    Stack<int> intStack;
    intStack.push(7);
    return EXIT_SUCCESS;
}

.h file

template<class T>
class Stack
{
    public:
        void push(T const& elem);
    protected:
    private:
        vector<T> m_elem;
};

.cpp file

template<class T>
void Stack<T>::push(T const& elem)
{
    m_elem.push_back(elem);
}

Error showing is

undefined reference to Stack<int>::push(int const&)

Can someone please help me. Thanking You in advance.

CherryDT
  • 25,571
  • 5
  • 49
  • 74
Govind
  • 17
  • 1
  • 1
    It is not possible to put the implementation of a template class into a separate source file, because it is materialized only "on demand" and it can't magically know what kinds of `T` another module will need (modules are compiled separately). Move it directly into the header file. – CherryDT May 19 '16 at 10:50

1 Answers1

2

You need to place the implementation of your template in your header-file, because they need to be inlined.

KimKulling
  • 2,654
  • 1
  • 15
  • 26
  • 1
    Inlined? Did you mean instantiated? – PcAF May 19 '16 at 10:59
  • 1
    No, when the compiler is using the template he needs to know which type shall be placed in the template. He generates code special for this template type. So this information must be there during compile time. So it must be placed in the header ( inlined ). – KimKulling May 19 '16 at 11:07
  • Oh you meant headers? I thought thay "they' refers to templates. – PcAF May 19 '16 at 11:22