Reputation: 13
I have one doubt on prefix operator overloading .
my sample program:
class ABC {
int i;
public:
const ABC& operator++() { i=i+1; return *this;}
};
int main() {
ABC ob ; //let value of i =5;
++ob; // value of i will be 6
return 0;
}
but I could do the same thing by overloading like below
void operator++() { i=i+1;}
this gives me same result when calling ++ob
APMK ++ob
converted as ob.operator++()
.
My doubt is what happens to the return value. Does the compiler creates code like:
ob = ob.operator++();
Thanks in advance
Upvotes: 0
Views: 544
Reputation: 264381
The reason to return a reference to an object is to make the behavior the same as for integers (for built in types).
std::cout << ++i;
std::cout << i++;
If i
is an integer this will work. This will only work in a class if you return a reference to the object (Assuming you have defined operator<<
for your class).
class ABC {
int i;
public:
ABC(int x = 0) : i(x) {}
const ABC& operator++() { i=i+1; return *this;}
ABC operator++(int) { ABC result(*this);i=i+1; return result;}
friend std::ostream& operator<<(std::ostream& out, ABC const& val)
{
return out << val.i;
}
};
With this definition then your class will behave the same way that an integer will behave in the above situation. Which makes it very useful when using template as you can now do a drop in replacement for integer with your type.
Note normally I would return just a reference (not a const reference).
/*const*/ ABC& operator++() { i=i+1; return *this;}
^^^^^^^^^
see: https://stackoverflow.com/a/3846374/14065
But C++ allows you do anything and you can return whatever is useful or has appropriate meaning for the situation. You should consider what is meaningful for your class and return a value that is appropriate. Remember the Principle of lease surprise
Upvotes: 0
Reputation: 4637
why do we have to return const reference from unary prefix operator overloading
You don't have to. Typically you return non-const reference, but you could make it return anything. You shouldn't, but you could. The built in pre-increment works how returning non-const reference works, so it makes the most sense to do that.
Upvotes: 1