i++ and ++i when the ++ operator is overriden

B

Binary

Hi,

In this board's FAQ, the operator override section says the i++ and ++i
has some difference, the i++ will make a copy of this pointer.
I can't know the reason, why?

Thanks in advance.
ABAI
 
K

Kai-Uwe Bux

Binary said:
Hi,

In this board's FAQ, the operator override section says the i++ and ++i
has some difference, the i++ will make a copy of this pointer.
I can't know the reason, why?

i++ is supposed to return the value of i *before* incrementing. So, if you
implement postincrement for a class, the typical implementation looks
somewhat like this:

class SomeIterator {

// ...

SomeIterator operator++ ( int ) {
// save the old value
SomeIterator return_value ( *this );
// increment
++ *this;
// return the old value
return( return_value );
}

};


Best

Kai-Uwe Bux
 
B

Binary

Perfect! Thank you!

ABAI
Kai-Uwe Bux said:
i++ is supposed to return the value of i *before* incrementing. So, if you
implement postincrement for a class, the typical implementation looks
somewhat like this:

class SomeIterator {

// ...

SomeIterator operator++ ( int ) {
// save the old value
SomeIterator return_value ( *this );
// increment
++ *this;
// return the old value
return( return_value );
}

};


Best

Kai-Uwe Bux
 
M

Michiel.Salters

Binary said:
Hi,

In this board's FAQ, the operator override section says the i++ and ++i
has some difference, the i++ will make a copy of this pointer.

/should/ make a copy. Each built-in operator++(int) makes a copy, and
your
versions should behave the same. The same applies to operator==; your
versions should return a bool. Else, people who use it would be
surprised.

I.e. it's not a technical requirement but a usability reason.

HTH,
Michiel Salters
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top