Jack in the Box
Jack in the Box

Reputation: 137

"Undefined symbols" error in C++

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...

Upvotes: 1

Views: 404

Answers (3)

Bo Persson
Bo Persson

Reputation: 92261

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); 

Upvotes: 0

Keldon Alleyne
Keldon Alleyne

Reputation: 2130

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

Upvotes: 0

nurettin
nurettin

Reputation: 11736

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

Upvotes: 2

Related Questions