Link to home
Start Free TrialLog in
Avatar of rzvika3
rzvika3

asked on

implementation differences between ++i and i++

Hi!
I create a class: Cl and i create an instance of it: temp_c.
I want to overide the two operators so that ++temp_c and temp_c++ will be a valid code.
1. can you give me the signatures of the two methods?
2. Is there a difference between the implementations of both operators? (I ask this because in ++temp_c, temp_c is first increased and in temp_c++ is increased only after the operation is done.
Thank you!
Avatar of gvg
gvg

Hi,

There is only one operator called operator++ and it is called for both cases.

Cl* Cl::operator++()
{
  // Do something.
  return this;
}


(I ask this because in ++temp_c, temp_c is first increased and in temp_c++ is increased only after the operation is done. )

This is almost true.  The word increased shouldn't be there because if you override the operator it might do something else.

a = temp++;

a is first assigned the value of temp then the operator++ is called and it might do something else.

But for

a = ++temp;

The operator is called first and then a is assigned the value of temp.

Hope this explains things
>> There is only one operator called operator++
>> and it is called for both cases.
That is not true.  You may overide both the pre-increment and the post-increment operators seperately.
The postfix form of operator++ (i++) takes an extra parameter, and int, that is not passed to the prefix form( ++i).  This int will always be passed as 0 and just serves to differentiate the two forms.  
Wrong,
1) there are two different operators for that with different signatures.
2) they (can) have different implementations

post-increment (i++)
   Cl  Cl::operator++(int)
           {Cl tmp(*this); ++(*this); return temp;}

pre-increment (++i)
   Cl& Cl::operator++()
           {this->do_increment(); return *this;}
I mean the proposed answer is wrong.
Avatar of rzvika3

ASKER

KangaRoo, take the point and thank you all!
ASKER CERTIFIED SOLUTION
Avatar of KangaRoo
KangaRoo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rzvika3

ASKER

You are welcome!