views:

127

answers:

6

I have a class called AString. It is pretty basic:

class AString
{
public:
    AString(const char *pSetString = NULL);
    ~AString();
    bool operator==(const AString &pSetString);
    ...

protected:
    char *pData;
    int   iDataSize;
}

Now I want to write code like this:

AString *myString = new AString("foo");
if (myString == "bar") {
    /* and so on... */
}

However, the existing comparison operator only supports

if (*myString == "bar")

If I omit that asterisk, the compiler is unhappy.

Is there a way to allow the comparison operator to compare *AString with const char*?

A: 

This question has already been raised before: Here

nakiya
It is not really obvious that and how the other question answers this question. The point is that an overloaded operator needs at least one non-primitive type, and that is only mentioned in answers to this question.
ndim
Whether this is correct or not, this should have been a comment.
sbi
+2  A: 

[ Original answer was wrong and thus corrected below ]

As pointed out by Oli Charlesworth, in a comment below, this is impossible.

You would need to define an operator like

   bool operator==(const AString *as, const char *cs); // Note: C++ will not do that

but you cannot overload an operator unless one of its parameters is non-primitive type - and pointers (both pointers to AString and pointers to char) are primitive types.

ndim
But doing this could lead to further surprises when comparing pointers afterwards!
Benoit
You can't overload operators unless one of them is a non-primitive type.
Oli Charlesworth
... that should say "non-member operators".
Oli Charlesworth
Well, member operators have an implicit parameter `this` to a non-primitive type, so I would say this holds for all operators.
ndim
@ndim: Good point.
Oli Charlesworth
+9  A: 

Not unless you wrap it in some sort of smart-pointer class, but that would make the semantics weird. What's wrong with if (*myString == "bar")?

Oli Charlesworth
+1  A: 

I think what you want is wrong since it obscures the type system of C++. myString is a pointer to a AString and not a AString. Dont't try to hide the fact that it's a pointer. It's an entry point for ugly bugs and if you're coding in a team everyone else would be nothing but confused!

Wolfgang Plaschg
+2  A: 
 if (myString == "bar")

even if you get it to work, is very confusing for others. You are comparing a pointer to an object with a string literal. A much clearer way to get this working is dereference the pointer, and provide an overload like

bool operator==(const char* pSetString);
stijn
+4  A: 

No, there is not.

To overload operator==, you must provide a user-defined type as one of the operands and a pointer (either AString* or const char*) does not qualify.
And when comparing two pointers, the compiler has a very adequate built-in operator==, so it will not consider converting one of the arguments to a class type.

Bart van Ingen Schenau