sushrut619 sushrut619 - 1 month ago 15
C++ Question

How does dereference operator (*) work when overloaded as a member function of a class?

When I looked up books and stack overflow article on operator overloading I found the following:

"When an overloaded operator is a member function, this is bound to the
left-hand operand. Member operator functions have one less (explicit)
parameter than the number of operands." - Addison Wesley, C++ Primer,

So my question is since the *(dereference) operator does not have any left operand, how does it get its parameter(which is the object itself or 'this') ?

Answer

For all prefix unary operator, it operates on the operand that follows it.

As an added question would there be any difference in how the overloaded * operator is used if it is defined as a non-member function vs a member function

For the most part, no, except that non-member function can't access private member of that class and if both the member function and non-member function existed, the member function has a higher rank, see ADL

For the reliable source, you can take a look at operator overloading, or, better, section 13.5.1 [over.unary] in the standard C++:

A prefix unary operator shall be implemented by a non-static member function (9.3) with no parameters or a non-member function with one parameter. Thus, for any prefix unary operator @, @x can be interpreted as either x.operator@() or operator@(x). If both forms of the operator function have been declared, the rules in 13.3.1.2 determine which, if any, interpretation is used. See 13.5.7 for an explanation of the postfix unary operators ++ and --. 2 The unary and binary forms of the same operator are considered to have the same name. [ Note: Consequently, a unary operator can hide a binary operator from an enclosing scope, and vice versa. —end note ]

For the selection if there are both member and non-member, see 13.3.1.2 [over.match.oper]

Comments