1

I'm trying to make a simple bounds checked array in C++. I have declared a class in a header file, and defined the class in a separate source file. The compile step runs fine, but when I try to link the objects, I get the following error:

$ g++.exe -o a.exe src\main.o src\array.o
src\main.o: In function `main':
../src/main.cpp:7: undefined reference to `Array<int>::Array(int)'
../src/main.cpp:9: undefined reference to `Array<int>::operator[](int)'
../src/main.cpp:10: undefined reference t o `Array<int>::operator[](int)'
../src/main.cpp:11: undefined reference t o `Array<int>::operator[](int)'
../src/main.cpp:13: undefined reference t o `Array<int>::operator[](int)'
../src/main.cpp:7: undefined reference to `Array<int>::~Array()'
../src/main.cpp:7: undefined reference to `Array<int>::~Array()'
collect2.exe: error: ld returned 1 exit status

main.cpp

#include <iostream>
#include "array.hpp"

using namespace std;

int main() {
  Array<int> x(10); // compiler error

  x[0] = 1; // compiler error
  x[1] = 2; // compiler error
  x[2] = 3; // compiler error

  cout << x[1] << endl; // compiler error

  return 0;
}

array.hpp

#ifndef ARRAY_HPP_
#define ARRAY_HPP_

template <class T>
class Array{
private:
  T* array;
  int length_;
public:
  Array(int);
  ~Array();
  int Length();
  int& operator[](int);
};

#endif /* ARRAY_HPP_ */

array.cpp

#include "array.hpp"

template <class T>
Array<T>::Array(int size) {
  length_ = size;
  array = new T[size];
}

template <class T>
Array<T>::~Array() {
  delete[] array;
}

template <class T>
int Array<T>::Length() {
  return length_;
}

template <class T>
int& Array<T>::operator[](const int index) {
  if (index < 0 || index >= length_) {
    throw 100;
  }
  return array[index];
}
Lily Mara
  • 3,859
  • 4
  • 29
  • 48

2 Answers2

1

Definitions of members of a template class shall be in the same header where the template class is defined itself.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Template classes must have all their code in the header file or they can only be used for types you explicitly instantiated in the cpp file.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42