Reputation: 3408
I was trying to implement a smart pointer class similar to the standard library auto_ptr and accordingly I had to overload the -> operator for the same. Here is my code
template <typename T>
class SmartPtr
{
T * operator -> ()
{
return _pAct;
}
private:
T * _pAct;
};
Rest of the implementation is not shown so as to avoid diversion from my query.
Now I create a SmartPtr of class A and call a method Show() present in A on it :
SmartPtr smPtr(new A);
smPtr->Show();
Here is my query(don't know if its valid also)
Since SmartPtr::operator->() return A*, the call to show should translate to (A*)Show. Why it translates to (A*)->Show() ?
or in other words how does smPtr->Show() mean call Show() on whatever smPtr->() operator returns ?
Upvotes: 1
Views: 194
Reputation: 258608
Because operator ->
applies sequentially until it can't be applied any more.
1)
operator->
shall be a non-static member function taking no parameters. It implements class member access using-> postfix-expression -> id-expression
An expressionx->m
is interpreted as(x.operator->())->m
for a class objectx
of typeT
ifT::operator->()
exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3). (emphasis mine)
Which means, in your case, it translates to:
smPtr.operator->()->Show();
| |
returns A* call Show on the A*
Upvotes: 4