The dereference operator works exactly the same way as an overloaded operator as it does as an ordinary operator.
int foo(int *p)
{
return *p;
}
In the statement return *p;
, the dereference operator applies to the pointer p
. It is passed to it on the right side:
As an overloaded operator, it works the same way.
class bar {
int *some_internal_ptr;
public:
int operator*() const {
return *some_internal_ptr;
}
// Other class members and methods...
};
int foo(bar p)
{
return *p;
}
When the right-hand side of the *
operator is class with an operator*` member, it gets invoked as an overloaded method of the class, no different than any other member, in order to resolve the dereference.
It is because the usage is identical is why many C++ library algorithms work equally well with either pointers or C++ library operators. For example, std::copy()
could be implemented as follows (I am trimming away some irrelevant complexity that's not germane here):
template<typename iter_type>
iter_type copy(iter_type b, iter_type e, iter_type t)
{
while (b != e)
{
*t=*b;
++t;
++b;
}
return t;
}
You can pass native pointers to std::copy
, or pass classes like iterators, with overloaded *
operators, and because an overloaded *
operator is used with the same syntax as an ordinary *
operator, the same algorithm works with the overloaded operator as well.