Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 523
bastibe Avatar asked Oct 06 '10 09:10

bastibe


People also ask

Can pointer be overloaded?

Functions can be overloaded depending on whether the parameter type is an interior pointer or a native pointer.

How do you overload a pointer in C++?

Class Member Access Operator (->) Overloading in C++ It is defined to give a class type a "pointer-like" behavior. The operator -> must be a member function. If used, its return type must be a pointer or an object of a class to which you can apply.

What is the correct way to overload operator?

In case of operator overloading all parameters must be of the different type than the class or struct that declares the operator. Method overloading is used to create several methods with the same name that performs similar tasks on similar data types.

Can we overload -> operator CPP?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions.


1 Answers

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.

like image 68
Bart van Ingen Schenau Avatar answered Sep 26 '22 15:09

Bart van Ingen Schenau