The objects sym2 e sym3 are considered equal because the attribute name is the same.
In some portions of the project code I'm using pointers to Symbol objects and I would prefer not to dereference theese pointers every time I have to test if two Symbol(s) are equal. In other words I would like to be able to write something like this:
Symbol *sym2 = new Symbol("due", true);
Symbol *sym3 = new Symbol("due", true);
if(sym2 == sym3) cout << "equal" << endl; // without the * operator before sym2 and sym3
else cout << "different" << endl;
In this case I'm not able to overload the == operator so that it can compare two Symbol objects using their pointers and not the objects themselves. I've tried to rewrite the == operator like this
but, although I've succesfully compiled the source code, the overloaded == operator member function doesn't get called and the equality test always fails because the standard == operator is used and the two addresses are, of course, different.
Looks like the formal and actual parameters types for the operatr== overload function do not match although the code compiles correctly.I'm beginnig to think that I'm missing something important here... Could anyone help me?
First, the argument to the == operator should be a const Symbol &.
Now, I think what you are suggesting could be accomplished by writing the operator as a non-member. However, I do not recommend that you follow through with this. Pointers are typically dereferenced to compare objects; saving yourself the extra step is likely to just obfuscate the conditionals.
Overloading the == operator for native C++ pointers is a bad idea - anyone reading the code would natually expect it to compare the addresses.
If you were creating a special purpose pointer class with this behavior, that == compared the objects pointed to (deep compare) that would be much less unusual. There's nothing wrong with "if(*sym2 == *sym3)" however; that's very natural code.
Alternatively, if you can use references (or simple stack variables) instead of pointers (and one ususally can), then operator== does what you want *with* the intuitive syntax.
I wasn't considering code readabilty which of course is very important. I'll stick with the working code for the overloading of the == operator an I'll duly dereference pointers when comparing objects.