1

I have Point class that has X, Y and Name as data members. I overloaded

T operator-(const Point<T> &);

This calculates the distance between two points and returns a value

template < typename T>
T Point<T>::operator-(const Point<T> &rhs)
{
cout << "\nThe distance between " << getName() << " and " 
<< rhs.getName() << " = ";

return sqrt(pow(rhs.getX() - getX(), 2) + pow(rhs.getY() - getY(), 2));;
}

The main function

int main () {

Point<double> P1(3.0, 4.1, "Point 1");

Point<double> P2(6.4, 2.9, "Point 2");

cout << P2 - P1;
return EXIT_SUCCESS;
}

But the problem is that this program doesn't compile, and I receive this error:

Undefined symbols:
"Point<double>::operator-(Point<double>&)", referenced from:
  _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

Any help is appreciated...

Jack in the Box
  • 137
  • 1
  • 1
  • 9

3 Answers3

2

You can't compile non-specialized templates. You have to put the definition code in headers.

nurettin
  • 11,090
  • 5
  • 65
  • 85
  • Templates can't be compiled as part of translation units by themselves. You need an instantiation or a specialization to compile them. – nurettin Jul 24 '12 at 10:31
  • duplicate: http://stackoverflow.com/questions/999358/undefined-symbols-linker-error-with-simple-template-class?rq=1 possible duplicates: http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file http://stackoverflow.com/questions/3749099/why-should-the-implementation-and-the-declaration-of-a-template-class-be-in-the?lq=1 – nurettin Jul 24 '12 at 11:00
  • I put the definition in .h file, and I still receive the same error! – Jack in the Box Jul 24 '12 at 11:50
0

You need to put your Point template class in a .hpp file and include that whenever using a Point.

Keldon Alleyne
  • 2,103
  • 16
  • 23
0

You have to include templates in each file that uses them, otherwise the compiler cannot generate the code for your specific type.

There is also a precedence between operators, which isn't changed when overloading them. Your code will be treated as

(cout << P2) - P1; 

Try this instead

cout << (P2 - P1); 
Bo Persson
  • 90,663
  • 31
  • 146
  • 203