0

I am learning object-oriented programming on my own. I am trying to implement a templated class. I am getting some linking error which I don't understand. My implementation is given below.

The Point.h contains a declaration of a Point class.

//Point.h
#pragma once
template <typename T>
class Point
{
        public:
                T x,y;
                Point();
                Point(T , T);
                Point(const Point<T>& P);
};

template <typename T>
Point<T> operator+ (const Point<T> & P1, const Point<T> & P2);

The member functions of Point class is implemented in Point.cpp

//Point.cpp
#include "Point.h"
template <typename T>
Point<T>::Point()
{}

template <typename T>
Point<T>::Point(T _x, T _y)
{
        x = _x;
        y = _y;
}

template <typename T>
Point<T>::Point(const Point<T> & P)
{
        x = P.x;
        y = P.y;
}

template <typename T>
Point<T> operator+ (const Point<T> & P1, const Point<T> & P2)
{
        Point<T> P3;
        P3.x = P1.x + P2.x;
        P3.y = P1.y + P2.y;
        return P3;
}

Now, I am testing the file in test-1.cpp.

//test-1.cpp
#include <iostream>
#include "Point.h"
using namespace std;

int main(int argc, char *argv[])
{
        Point<double> A(0,0), B(1,1), C;
        C = A+B;
        cout << C.x << endl;

        return 0;
}

When I try to compile the test-1.cpp as

g++ Point.cpp test-1.cpp

It gives some linking error,

/usr/sbin/ld: /tmp/cccV74gb.o: in function `main':
test-1.cpp:(.text+0x2e): undefined reference to `Point<double>::Point(double, double)'
/usr/sbin/ld: test-1.cpp:(.text+0x52): undefined reference to `Point<double>::Point(double, double)'
/usr/sbin/ld: test-1.cpp:(.text+0x5e): undefined reference to `Point<double>::Point()'
/usr/sbin/ld: test-1.cpp:(.text+0x75): undefined reference to `Point<double> operator+<double>(Point<double> const&, Point<double> const&)'
collect2: error: ld returned 1 exit status

What disturbs me most is the last error, where the compiler looks for + < double > operator which I never defined. I have only overloaded + operator.

How to properly implement member and non-member functions with templates?

Galilean
  • 246
  • 4
  • 15

0 Answers0