Undefined reference error

I have the following class declared in a header file named calculation.h:

namespace Calc
{
template <class T, class E, class Q>
class Calculation
{
private:
T a;
E b;
Q result;

Q& add();
Q& sub();
Q& mul();
Q& div();

public:
Calculation(const T& first,const E& second) : a(first),b(second){};
Q& calculate(const char& op);
};
;
}

When I attempt to use the calculate function, I get the undefined reference error. It seems that the compiler doesn't recognize that the calculate function is implemented in the source file calculation.cpp, because if I copy the implantation into the header file for all the class functions, the error disappears.

Here is how I implemented it in the source file:
#include "calculation.h"
using namespace Calc;

/*****************************************************************/
template <class T, class E, class Q>
Q& Calculation<T, E, Q>::calculate(const char& op)
{
switch (op) {
case '+':
return add();
break;
case '-':
return sub();
break;
case '*':
return mul();
break;
case '/':
return div();
break;
default:
break;
}

}
/**********************************************************************/

Any one has any idea for how to fix it?

Last edited on
Change the extension of the .c file to a .cpp file.
Sorry it's already cpp, wrote .c by accident in the original post =P
Last edited on
are you linking to calculation.cpp? Is it part of your project?

Oh durr.. it's a template.

You can't put template definitions in cpp files. the whole thing must go in your header.


(also... this is unrelated, but it seems strange that you're returning references everywhere)
Last edited on
There is an article about this, but I can't find it.
This is the idea:
You can't have a cpp if you work with templates. However if you want to have separate file with the implementation do this
#include "calculation.hpp" at the end of the header file (I change the extension)
Ok thanks for the answers =)

I return reference because so far I saw no reason not to. If I see that I return local values as reference I will change it.

Q& add();
Q& sub();
Q& mul();
Q& div();

I return reference because so far I saw no reason not to. If I see that I return local values as reference I will change it.


Not only that but by returning Q& that is reference to *this, you allow nested calls on your object.

Calculation calc;

calc.add().sub().mul().div();

Cool isn't it :)
Topic archived. No new replies allowed.