0

I have a dynamic array-based class that I'm calling MyList, that looks as follows:

#ifndef MYLIST_H
#define MYLIST_H
#include <string>
#include <vector>

using namespace std;

template<class type>
class MyList
{
public:
  MyList(); 
  ~MyList(); 
  int size() const;
  type at() const;
  void remove();
  void push_back(type);

private:
  type* List;
  int _size;
  int _capacity;
  const static int CAPACITY = 80;
};

#endif

I also have a another class that I'm calling User that I want to include an instance of MyList as a private data member. User looks like this:

#ifndef USER_H
#define USER_H
#include "mylist.h"
#include <string>
#include <vector>

using namespace std;

class User
{
public:
  User();
  ~User();

private:
  int id;
  string name;
  int year;
  int zip;
  MyList <int> friends;
};

#endif

When I try to compile I get an error in my user.cpp file:

undefined reference to MyList::Mylist()

I find this odd because MyList is completely unrelated to user.cpp, which only contains my User constructor and destructor.

Mat
  • 202,337
  • 40
  • 393
  • 406
Daniel Hwang
  • 1
  • 1
  • 2
  • 2
    Do you ever implement the constructor? – David G Feb 10 '13 at 14:44
  • 3
    Class template's definitions must be available when instantiating them. You can't define your template in a source file as you usually do with non-template classes. Move the definition into the header file, or include the definition from the header file. – mfontanini Feb 10 '13 at 14:46
  • possible duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Mat Feb 10 '13 at 14:46

2 Answers2

1

Make sure that you write both the declaration and the definition of your template class into the header (define MyList in the header not in a .cpp file)

Zlatomir
  • 6,964
  • 3
  • 26
  • 32
0

The reason is that you did not provide MyClass<int> constructor definition. Unfortunatelly in C++ you cannot divide template class definition by declaring methods in header file and defining them in the implementation. At least if you want to use it in other modules. So in your case User class needs to have MyClass<int>::MyClass() definition right now. There are two ways to do it:

  1. (the easiest one) provide constructor definition right in place: MyClass() { ... } or

  2. add method definition in MyClass.h after class definition like that: template<class type> MyList<type>::MyList() { ... }

y0prst
  • 611
  • 1
  • 6
  • 13