2

Possible Duplicate:
Why do I get “unresolved external symbol” errors when using templates?

LinkedList.h

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include<iostream>

template<class T> class LinkedList;

//------Node------
template<class T>
class Node {
private:
    T data;
    Node<T>* next;
public:
    Node(){data = 0; next=0;}
    Node(T data);
    friend class LinkedList<T>;

};


//------Iterator------
template<class T>
class Iterator {
private:
    Node<T> *current;
public:

    friend class LinkedList<T>;
    Iterator operator*();
 };

//------LinkedList------
template<class T>
class LinkedList {
private:
    Node<T> *head;


public:
    LinkedList(){head=0;}
    void push_front(T data);
    void push_back(const T& data);

    Iterator<T> begin();
    Iterator<T> end();

};



#endif  /* LINKEDLIST_H */

LinkedList.cpp

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


using namespace std;

//------Node------
template<class T>
Node<T>::Node(T data){
    this.data = data;
}


//------LinkedList------
template<class T>
void LinkedList<T>::push_front(T data){

    Node<T> *newNode = new Node<T>(data);

    if(head==0){
        head = newNode;
    }
    else{  
        newNode->next = head;
        head = newNode;
    }    
}

template<class T>
void LinkedList<T>::push_back(const T& data){
    Node<T> *newNode = new Node<T>(data);

    if(head==0)
        head = newNode;
    else{
        head->next = newNode;
    }        
}


//------Iterator------
template<class T>
Iterator<T> LinkedList<T>::begin(){
    return head;
}

template<class T>
Iterator<T> Iterator<T>::operator*(){

}

main.cpp

#include "LinkedList.h"

using namespace std;


int main() {
    LinkedList<int> list;

    int input = 10;

    list.push_front(input); 
}

Hi, I am fairly new at c++ and I am trying to write my own LinkedList using templates.

I followed my book pretty closely and this is what I got. I am getting this error though.

/main.cpp:18: undefined reference to `LinkedList::push_front(int)'

I have no clue why, any ideas?

Community
  • 1
  • 1
Instinct
  • 2,201
  • 1
  • 31
  • 45
  • This is caused by the same issue as the problem described here: http://stackoverflow.com/questions/13150412/undefined-symbol-on-a-template-operator-overloading-function – jogojapan Nov 04 '12 at 07:25
  • Which book didn't tell you that you have to put template code in the header file? – john Nov 04 '12 at 07:37

1 Answers1

6

You are using templates in your Program. When you use templates, you have to write the code and the headers in the same file because the compiler needs to generate the code where it is used in the program.

You can do either this or include #inlcude "LinkedList.cpp" in main.cpp

This question might help you. Why can templates only be implemented in the header file?

Community
  • 1
  • 1
Coding Mash
  • 3,338
  • 5
  • 24
  • 45