Search code examples
c++pointersoperator-overloadingcomparison-operators

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


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


Solution

  • 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.