Why does this call to arrow (->) operator fail?

  • A+
Category:Languages

Consider the following code :

#include <iostream>  class Test { public:     Test() : a{ 0 }     {}      void print() const     {         std::cout << "a : " << a << std::endl;     }      void operator->()     {         a = 5;     }      void operator++()     {         ++a;     }  public:     int a; };  int main() {     Test a;     a.print();      // Increment operator     a.operator++();      // CORRECT     ++a;                 // CORRECT     a.print();      // Indirection operator     a.operator->();      // CORRECT     a->;                 // INCORRECT     a.print(); } 

Why is the call to the second -> operator incorrect? I know this usage of -> is different from the general usage, but is such usage disallowed by the standard?

 


The sub-section on Class member access from Overloaded Operators from CPP standard draft (N4713) states this:

16.5 Overloaded operators
...
16.5.6 Class member access [over.ref]
1. operator-> shall be a non-static member function taking no parameters. It implements the class member access syntax that uses ->.

postfix-expression -> template(opt) id-expression //This!! postfix-expression -> pseudo-destructor-name 

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 (16.3).

As you can see the id-expression is very much needed if the -> operator is overloaded.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: