1

I'm trying to create a linked list, but when I run IsEmpty(test) it just says it was not declared in this scope even though it's public.

I'm pretty new at templates, but I couldn't find the answer on google so I have to ask here. Anyone know what the problem is?

Also, the error points to main() where I call IsEmpty()

//.h
template <typename ItemType>
class Node
{
    public:
        ItemType Data;
        Node <ItemType> *next;
        int position;
};

template <typename ItemType>
class Linked_List
{
        public:
        Node <ItemType> *start;
        Linked_List();
        bool IsEmpty();
}


//.cpp  
#include "Linked_List.h"
#include <iostream>
#include <cstdlib>
using namespace std;

template <typename ItemType>
Linked_List <ItemType>::Linked_List(){
    start = NULL;
}

template <typename ItemType>
bool Linked_List <ItemType>::IsEmpty(){
    if (start == NULL){
        return true;
    }
    return false;
}

int main(){
    Linked_List <int> test;
    cout << IsEmpty(test) << endl;   //error points to here
}
Seb
  • 1,966
  • 2
  • 17
  • 32

3 Answers3

2

The correct way to invoke a member function is obj.function(...). You need:

cout << test.IsEmpty() << endl;   //error points to here
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

Templates have to be declared and defined in header files.

kaman
  • 376
  • 1
  • 8
  • I see, it seems to be working fine though. Any reason why? Edit:nvm just saw that link posted – Seb May 08 '14 at 15:18
  • http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file this should answer your question – kaman May 08 '14 at 15:21
0

Template headers do not work as non-template headers. You must define your template functions inside the header. Just move the definitions you have on the .CPP file to the end of your .h file.

After you have done that you can invoke the function from the object you have created.

jRobin
  • 11
  • 2