0

I am trying to create a class linkedList using template but when I compile it the IDE gives an error : undefined reference to `listType::add(int) I am not understanding why ?

linkedList.h

#ifndef LINKEDLISTS_H_INCLUDED
#define LINKEDLISTS_H_INCLUDED
#include "struct.h"
template <class type1>

class listType
{
public:

void add(type1);
void print();
private:
node<type1> *head;
};


#endif // LINKEDLISTS_H_INCLUDED

LinkedList.cpp

#include "linkedLists.h"
#include "struct.h"
#include <iostream>
using namespace std;

template <class type1>
void listType<type1>::add(type1 temp)
{
node<type1> *t;
t->value=temp;
t->link=head;
head=t;
}
template <class type1>
void listType<type1>::print()
{
node<type1> *p;
p=head;
while(p!=NULL)
{

    cout<<p->value<<endl;
    p=p->link;
}

}

Struct.h

#ifndef STRUCT_H_INCLUDED
#define STRUCT_H_INCLUDED
template <class type1>

struct node
{

type1 value;
node *link;
};


#endif // STRUCT_H_INCLUDED

main.cpp

#include <iostream>
#include "linkedLists.h"
using namespace std;


int main()
{
listType <int> test;
test.add(5);

}

MRBULL93
  • 141
  • 1
  • 4
  • 12

1 Answers1

2

You can't have the implementation of templated classes and functions in the cpp file.

The code has to be in the header, so the including files can see the implementation, and instantiate the correct version with their template argument type.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185