Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of operator++ [duplicate]

Tags:

People also ask

Does += return the new value?

In general, an operator whose result is a new value (such as +, -, etc) must return the new value by value, and an operator whose result is an existing value, but modified (such as <<, >>, +=, -=, etc), should return a reference to the modified value.

What is the return value of == operator?

Each of the operators yields 1 if the specified relation is true and 0 if it is false.

What should ++ operator return?

The inner operator++ call returns a temporary Number object. The outer operator++() expects a parameter of type Number& - but a non-const reference can't bind to a temporary.

Why does operator return * this?

The & in the Poly& Poly::operator= declaration means that the operator returns a reference - to itself in this case, which is precisely what return *this; does. On the other hand, the & in &p1 evaluates to the address of p1 , which is a Poly* pointer, and cannot be assigned to a Poly object.


I have the following code that is broken. I can fix it by modifying certain line in code (see the comment). What is the cause of the problem?

#include <iostream>
using namespace std;

class Number{
public:
    int n;
    Number(int a):n(a){}

    //when I change the following to
    //friend Number& operator++(Number& source, int i)
    //then it compiles fine and correct value is printed
    friend Number operator++(Number& source, int i){
        ++source.n;
        return source;
    }
};

int main() {

    Number x(5);
    x++++; //error: no 'operator++(int)' declared for postfix '++' [-fpermissive]
    cout<<x.n;

    return 0;
}