Reputation: 423
I am learning the operator overloading functionality in C++ and I have come accross a problem. Here is my code:
template <typename T>
class W
{
public:
bool operator==(W&);
T x;
};
template <typename T>
bool W<T>::operator==(W& w2)
{
printf("\n%d, %d\n", x, w2.x);
if(x == w2.x) return true;
else return false;
}
int main()
{
W<int>* w1 = new W<int>;
W<int>* w2 = new W<int>;
w1->x = 10;
w2->x = 10;
if(w1 == w2) printf("same");
else printf("not");
}
The result is however 'not'. And the printf function is not called in the overloaded bool function. If I initialize the objects this way:
W<int> w1;
W<int> w2;
w1.x = 10;
w2.x = 10;
it works. But in my case I only use the first example objects (in my other project). So my question is how do I pass objects and it would work. Thanks.
Upvotes: 0
Views: 128
Reputation: 311156
Your definition of the operator is not good. The better its declaration could look the following eay
bool operator==( const W &) const;
and corresponding realization
template <typename T>
bool W<T>::operator ==( const W &w2 ) const
{
printf("\n%d, %d\n", x, w2.x);
return ( x == w2.x );
}
In your code you compare pointers but must compare objects theirself. So the correct syntax will be
if ( *w1 == *w2 ) ...
Upvotes: 0
Reputation: 15870
You are not comparing objects in your code, but addresses to objects (pointers). There is no need for these objects to be dynamically allocated:
int main()
{
W<int> w1;
W<int> w2;
w1.x = 10;
w2.x = 10;
if(w1 == w2)
printf("same");
else
printf("not");
}
Additionally, you can change your return value from your overloaded operator:
template <typename T>
bool W<T>::operator==(const W& w2) const // note: it should be declared as const
{
printf("\n%d, %d\n", x, w2.x);
return x == w2.x;
}
Upvotes: 2
Reputation: 258678
You're comparing pointers, not objects, so your operator is never called.
Do
*w1 == *w2
or
w1->operator==(*w2);
Or no dynamic allocation at all
W<int> w1;
W<int> w2;
w1.x = 10;
w2.x = 10;
Also note that the signature for operator==
should be
bool operator==(const W&) const
since it modifies neither of the operands.
Upvotes: 4