I'm wanting to make sure I understand pass-by-value vs pass-by-reference properly. In particular, I'm looking at the prefix/postfix versions of the increment ++
operator for an object.
Let's suppose we have the following class X
:
class X{ private: int i; public: X(){i=0;} X& operator ++ (){ ++i; return *this; } //prefix increment X operator ++ (int unused){ //postfix increment X ret(*this); i++; return ret; } operator int(){ return i; } //int cast };
First of all, have I implemented the prefix/postfix increment operators properly?
Second, how memory-efficient is the postfix operator, compared to the prefix operator? Specifically how many X
object copies are created when each version of the operator is used?
An explanation of exactly what happens with return-by-reference vs return-by-value might help me understand.
Edit: For example, with the following code...
X a; X b=a++;
...are a and b now aliases?
The prefix increment operator (++) adds one to its operand; this incremented value is the result of the expression. The operand must be an l-value not of type const . The result is an l-value of the same type as the operand.
prefix vs postfix. In java, the prefix increment operator increases the value and then returns it to the variable. The prefix decrement operator will first decrement the value before returning it to the variable. The postfix increment operator returns the value to the variable before incrementing it.
Postfix operators are unary operators that work on a single variable which can be used to increment or decrement a value by 1(unless overloaded). There are 2 postfix operators in C++, ++ and --.
In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent. i=5; i++; printf("%d",i);
It is more idiomatic to call the prefix increment of the object itself in the postfix increment:
X operator++(int) { X copy(*this); ++*this; // call the prefix increment return copy; }
The logic of incrementing an X
object is thus solely contained inside the prefix version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With