-1
//includes, using etc.
int main()
{
    List<int> a;
    cout << a.size() << endl;
    return 0;
}


//list.h
template <class T>
class List{

int items;

public:
List();
~List();

int size() const;

};

//list.cpp
#include "list.h"
template<class T>
List<T>::List() :
items(0)
{}

template<class T>
List<T>::~List()
{}

template<class T>
int List<T>::size() const
{   return items;   }

This should work, shouldn't it? When I define list.h's and list.cpp's content above the main function, everything works fine. However, this gives me some errors :

main.cpp:(.text+0x12): undefined reference to List<int>::List()'
main.cpp:(.text+0x1e): undefined reference to
List::size() const'
main.cpp:(.text+0x4f): undefined reference to List<int>::~List()'
main.cpp:(.text+0x64): undefined reference to
List::~List()'

when I change List<int> a; in the main function to List<int> a(); the only Error I get is this :

main.cpp:10:12: error: request for member ‘size’ in ‘a’, which is of non-class type ‘List()’

Help me, what'S wrong?

Davlog
  • 2,162
  • 8
  • 36
  • 60

1 Answers1

1

List is a template class and (most of the times) this means that its code must be in the header file.

In addition,

List<int> a();

is the declaration of a function called a that returns a List<int>. I emphasize: a is not a default-initialized object of type List<int>.

Cassio Neri
  • 19,583
  • 7
  • 46
  • 68