1

Following is compiled OK in both gcc and clang:

class A{
public:
    void operator++(){
        printf("A++\n");
    //  return *this;
    }
};

Doesn't "correct" way to implement this kind of operator be:

class A{
public:
    A &operator++(){
        printf("A++\n");
        return *this;
    }
};

Is void version a hack? I never saw syntax like this. Google search returns only one educational IBM paper about it.

Why this is not wide used way to implement pre-increments against returning self reference.

Nick
  • 9,962
  • 4
  • 42
  • 80

2 Answers2

6

Why this is not wide used way to implement pre-increments against returning self reference.

If you're asking why it is pre-increment doesn't have this signature, instead of returning an lvalue reference to the object it is applied to, it is because it is designed to evaluate to an expression, such that it can be used in the same way as it is for built-in types:

int i = 42;
int j = ++i;
A a;
A b = ++a;           // Error if RHS is void
(++a).doSomething(); // ditto

Furthermore, the expected semantics of prefix ++ (and --) is that they return an lvalue reference to the (modified) object. To do anything different will invariably lead to confusion.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

You can certainly write it this way, and it will do what you want. But there is a general principle for design that overloaded operators should work in a similar way to how 'int' would work to avoid surprised users.

People would expect to be able to write

A a;
B b = ++a;

Because that's how pre-increment usually works, and would be surprised by the compiler error this would give with your class. There is no technical reason why you can't make it do something different, in the same way that you can make operator + do subtraction for your class if you really want.

jcoder
  • 29,554
  • 19
  • 87
  • 130