• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 185
  • Last Modified:

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!
0
rzvika3
Asked:
rzvika3
  • 3
  • 2
  • 2
  • +1
1 Solution
 
gvgCommented:
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
0
 
nietodCommented:
>> 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.
0
 
nietodCommented:
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.  
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
KangaRooCommented:
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;}
0
 
KangaRooCommented:
I mean the proposed answer is wrong.
0
 
rzvika3Author Commented:
KangaRoo, take the point and thank you all!
0
 
KangaRooCommented:
Ok, thanx!
0
 
rzvika3Author Commented:
You are welcome!
0

Featured Post

Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now