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

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

 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 the asterisk, the compiler is unhappy.

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

+6
c ++ pointers comparison-operators operator-overloading
source share
5 answers

No no.

To overload operator== , you must specify a user-defined type, since one of the operands and a pointer (either AString* or const char* ) do 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.

+8
source share

Not unless you wrap it in some class of smart pointers, but that will make the semantics weird. What happened to if (*myString == "bar") ?

+10
source share

I think you want to be wrong, as it hides the C ++ type system. myString is a pointer to an AString , not a AString . Do not try to hide the fact that this is a pointer. This is the entry point for ugly mistakes, and if you code in a team, everyone else will be no more than embarrassed!

+3
source share
  if (myString == "bar") 

even if you earn it, it confuses others a lot. You are comparing a pointer to an object with a string literal. A clearer way to get this working is to dereference the pointer and provide overload, e.g.

 bool operator==(const char* pSetString); 
+3
source share

[The original answer was incorrect and thus was fixed below]

As Oli Charlworth noted, in the comment below this is not possible.

You will need to define a type operator

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

but you cannot overload a statement if one of its parameters is not a primitive type - and pointers (both pointers to AString and pointers to char) are primitive types.

+2
source share

All Articles