Search code examples
c++pointersoperator-overloadingthisdereference

When the dereference operator (*) is overloaded, is the usage of *this affected?


For example,

class Person{
        string name;
    public:
        T& operator*(){
            return name;
        }
        bool operator==(const Person &rhs){
            return this->name == rhs.name;
        }
        bool operator!=(const Person &rhs){
            return !(*this == rhs); // Will *this be the string name or the Person?
        }
}

If *this ends up dereferencing this to a string instead of a Person, is there a workaround that maintains the usage of * as a dereference operator outside the class?

It would be quite a hindrance if I couldn't overload * without giving up usage of *this.


Solution

  • If *this ends up dereferencing this to a string instead of a Person, is there a workaround that maintains the usage of * as a dereference operator outside the class?

    No. *this will be Person& or Person const& depending on the function. The overload applies to Person objects, not pointers to Person objects. this is a pointer to a Person object.

    If you use:

     Person p;
     auto v = *p;
    

    Then, the operator* overload is called.

    To call the operator* overload using this, you'll have to use this->operator*() or **this.