How to overload operator==() for a pointer to the class?

bastibe picture bastibe · Oct 6, 2010 · Viewed 14.5k times · Source

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*?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Oct 6, 2010

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")?