28

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.

2 Answers2

43

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
12

You need an object of the class rather than the pointer to class object to invoke the overloaded * operator.

Person *ptr = new Person;
Person p1 = *ptr;   // does not invoke * operator but returns the object pointed by ptr
string str = *p1 // invokes the overloaded operator as it is called on an object.

Same is the case with this pointer. To invoke * operator with this pointer, you will have to dereference twice:

std::string str = *(*this);
Ajay
  • 18,086
  • 12
  • 59
  • 105
shainu vy
  • 181
  • 1
  • 8