Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What does the dereference operator (*) do?

In computer programming, a dereference operator, also known as an indirection operator, operates on a pointer variable. It returns the location value, or l-value in memory pointed to by the variable's value.

Can dereference operator be overloaded?

The dereference operator ( * ) overload works like any other operator overload. If you want to be able to modify the dereferenced value, you need to return a non-const reference. This way *sp = value will actually modify the value pointed to by sp. pData and not a temporary value generated by the compiler.

Which operator is used to dereference of pointer?

The unary operator * is used to declare a pointer and the unary operator & is used to dereference the pointer.. In both cases, the operator is “unary” because it acts upon a single operand to produce a new value.

What is the difference between address (&) and dereference (*) operator?

We can use the addressoperator to obtain its address, whatever it may be. This address can be assigned to a pointervariable of appropriate type so that the pointer points to that variable. The dereference operator (*) is a unary prefix operator that can be used with any pointer variable, as in *ptr_var.


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.


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);