The IsEqualTo function is a global function (it appears) and so it isn't const and shouldn't be const. A function being const only makes sense if it is a member function. That is why your operator== needed to be const. It was implemented as a member function. When you call a member function using a const reference or object, that function must be declared as const (this makes sense, you have a const reference so you promise not to change it, and you can only call const functions that promise not to change it).
A reference can be const or non-const, and you can initialize a const reference with a non-const object.
Code:
class Test {
public:
void ModifyMe() { /* Do something to modify me */ }
void DontModifyMe() const { /* Read-only operations */ }
};
int main()
{
Test tInst;
const Test constInst;
Test& refToInst = tInst; // Fine, non-const reference to non-const object.
const Test& constRefToInst = tInst; // Fine, const reference to non-const object.
//Test& refToConstInst = constInst; // ERROR!! Non-const reference to const object.
const Test& constRefToConstInst = constInst; // Fine, const reference to const object.
tInst.ModifyMe(); // Fine, call non-const function from non-const object.
//constInst.ModifyMe(); // ERROR!! Call non-const function from const object.
refToInst.ModifyMe(); // Fine, call non-const function from non-const reference.
//constRefToInst.ModifyMe(); // ERROR!! Call non-const function from const reference.
//constRefToConstInst.ModifyMe(); // ERROR!! Call non-const function from const reference.
tInst.DontModifyMe(); // Fine, call const function from non-const object.
constInst.DontModifyMe(); // Fine, call const function from const object.
refToInst.DontModifyMe(); // Fine, call const function from non-const reference.
constRefToInst.DontModifyMe(); // Fine, call const function from const reference.
constRefToConstInst.DontModifyMe(); // Fine, call const function from const reference.
}
So in your code:
Code:
template <class T>
bool isEqualTo( const T &left, const T &right )
{
return ( left == right );
}
Note that the above is equivalent to:
Code:
template <class T>
bool isEqualTo( const T &left, const T &right )
{
return ( left.operator==(right) );
}
You have a const reference, left, calling a member function, bool operator==( const HugeInt &op2 ), that wasn't const. That is like the line above:
//constRefToInst.ModifyMe(); // ERROR!! Call non-const function from const reference.
When you add the const to the operator==, you see that it works like this line:
constRefToInst.DontModifyMe(); // Fine, call const function from const reference.
Of course, then once you understood why it wasn't working before, you changed operator== to not be a member function like Prelude suggested, and you stopped having to worry about member function constness for this problem.