making operator == work with pointers ?

Started by
4 comments, last by bilsa 20 years ago
Hey guys! I was overloading the == operator for a class of mine and noticed that the operator is never used. I guess it''s because when I create an object with new and store the adress in a pointer I I never actually have an object of my type in the pointer. So when I call the == on the pointer, its the pointers operator that is used rather than mine. So is there any way to fix this other than overloading the public == operator for pointers? what I want to do is:

MyClass* obj1 = new MyClass();
MyClass* obj2 = new MyClass();

//And here I want MyClass'' operator== to be used rather than

//the operator== for pointers (or adress'' or whatever...) 

if(obj1 == obj2)...
thx !
Advertisement
Try dereferncing the pointers before you check for equality. i.e.: (*obj1 == *obj2).
if(obj1 == obj2) // compares the pointers themselves (i.e. just an address)

if(*obj1 == *obj2) // compares what they point to
Brianmiserere nostri Domine miserere nostri
Yes thx, I figured that out too.

But I would want to be able to use the syntax like this:
(obj1 == obj2), not (*obj1 == *obj2)

It's just for the eye
looks better with obj1 == obj2 rather than the second variant...

[edited by - bilsa on April 4, 2004 8:02:16 PM]
quote:Original post by bilsa
Yes thx, I figured that out too.

But I would want to be able to use the syntax like this:
(obj1 == obj2), not (*obj1 == *obj2)

It''s just for the eye
looks better with obj1 == obj2 rather than the second variant...


It looks different because it IS different. The first simply compares two memory addresses, to see if they''re pointing to the same *place* in memory. The second compares the objects that two pointers are pointing at to see if the two objects have the same *contents* (assuming you wrote your operator function correctly).

Brianmiserere nostri Domine miserere nostri
So is there any way to fix this other than overloading the public == operator for pointers?

You can''t overload operators for built-in types (such as pointers). There is no way to achieve what you are trying to do (at least with real pointer and not proxy objects). Just give up.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement