Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can I use scalar type as the return type of operator->?

From cppreference:

The overload of operator -> must either return a raw pointer, or return an object (by reference or by value) for which operator -> is in turn overloaded.

However, I tested the following example, and it is accepted by GCC, Clang and MSVC:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct A {
  int operator->();
};

According to cppreference, the return type int is neither a pointer nor a type that overloads operator->.

Why is this example correct? Where is this situation described in the standard? What is the intent of the standard to allow this?

>Solution :

While the standard doesn’t directly place restrictions on the return type of operator->, it does describe what happens when the overloaded -> operator is used:

12.6.5 Class member access [over.ref]

A class member access operator function is a function named operator-> that is a non-static member function taking no parameters. For an expression of the form
    postfix-expression -> template(opt) id-expression
the operator function is selected by overload resolution (12.4.1.2), and the expression is interpreted as
     ( postfix-expression . operator -> () ) -> template(opt) id-expression.

So when using your class, you can call the overloaded operator like a normal function by writing a.operator->(). But if you attempt to use the operator with a->name, this is interpreted as (a.operator->())->name which won’t compile because it attempts to use -> on an int.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading