VansFannel
VansFannel

Reputation: 45921

Template Type is undefined

I'm learning C++ and now I'm working with Template.

I'm trying to implement a Linked List:

ListElement.hpp

#ifndef LIST_ELEMENT_HPP_
#define LIST_ELEMENT_HPP_

template <class Type> class SingleLinkedList;

template <class Type>
class ListElement
{
public:
    ListElement(const Type element);
    ~ListElement(void);
public:
    Type val;
    ListElement* next;
};

#endif

ListElement.cpp:

#include "ListElement.hpp"

ListElement<Type>::ListElement(const Type element)
{
     *next = NULL;
     val = element;
}


ListElement<Type>::~ListElement(void)
{
}

I'm getting an Error on ListElement.cpp releated to Type: Type is undefined.

I have found a lot of examples about how to implement a Linked List but none using a separated hpp and cpp.

Do you know how can I fix this error?

Upvotes: 1

Views: 448

Answers (3)

Andy Prowl
Andy Prowl

Reputation: 126452

First problem:

You need to fix the way you are defining the member functions of your class template:

template<typename Type> // <== ADD THIS!
ListElement<Type>::ListElement(const Type& element)
//                                       ^
//                                       And perhaps also this?
//                                       (don't forget to modify the
//                                       corresponding declaration if 
//                                       you change it)
{
     *next = NULL;
     val = element;
}

Second problem:

You should move those definitions to the same header file that contains the definition of the class template, or the linker will complain about undefined references. For more information, see this Q&A on StackOverflow.

Third problem:

In your constructor, you are currently causing undefined behavior by dereferencing an uninitialized pointer. You shouldn't be doing:

*next = NULL;
^^^^^^^^^^^^^
Undefined Behavior! next is uninitialized and you are dereferencing it!

But rather:

next = NULL;

Or even better (using constructor initialization lists and C++11's nullptr):

template<typename Type>
ListElement<Type>::ListElement(const Type& element) :
    val(element),
    next(nullptr)
{
}

Upvotes: 2

ForEveR
ForEveR

Reputation: 55887

Firstly - in general you cannot split declaration and implementation of template class in different files. Secondly - before implementation should be template decl.

template<typename Type>
ListElement<Type>::ListElement(const Type element)
{
     next = NULL;
     val = element;
}

Upvotes: 1

43l0v3k
43l0v3k

Reputation: 337

At first try to add

template<class Type>

before each function in .cpp file

It wouldn't work. (Linker errors) So move all your implementation to .h file.

Then perhaps you should change

ListElement(const Type element);

to

ListElement(const Type &element);

Upvotes: 0

Related Questions