1

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 ?

0

1 Answer 1

4

Because operator -> applies sequentially until it can't be applied any more.

13.5.6 Class member access [over.ref]

1) operator-> shall be a non-static member function taking no parameters. It implements class member access using -> postfix-expression -> id-expression An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::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*
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.