Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefix/Postfix increment operators

Tags:

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?

like image 646
Cam Avatar asked Jul 05 '10 17:07

Cam


People also ask

What is prefix increment operator?

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.

What is the difference between prefix and postfix increment operators in Java?

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.

Is ++ a postfix operator?

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 --.

What is ++ i and i ++ in C?

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);


1 Answers

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.

like image 159
fredoverflow Avatar answered Oct 14 '22 06:10

fredoverflow