I saw this C++ code as part of a larger example:
Date &Date::operator++()
{
helpIncrement();
return *this;
}
Date Date::operator++( int )
{
Date temp = *this;
helpIncrement();
return temp;
}
Firstly if Date temp = *this, then I dont see why the return type is any different for these two functions? One returns *this, the other returns temp, which is assigned to *this?
Secondly, why does the parameter for the second function not have a variable name?
The first returns the object pointed to by
thisas a reference. That is, the returned object is the object thatoperator++is being called on. However, when you doDate temp = *this,tempis copy constructed from the value of*this. It is in turn then copied out of the function. What you get from the second function is a whole new object. Why the functions have this difference is explained in the answer to your second question.There are two types of increment operator – one is post-increment (
i++) and the other is pre-increment (++i). To be able to overload each of them individually (despite them having the same name,operator++), the C++ standard specifies that the post-increment operator takes an argument of typeintwith unspecified value. This is simply so that you can overload the function for each use of the operator. Since you’re unlikely to want to use that unspecified value, you may as well just leave it unnamed.Now, the expected behaviour of the pre-increment operator is that it increments the object and evaluates to then be that object. That’s why it returns a reference in this case. The expected behaviour of post-increment is that it keeps a copy of the original value, increments the object and then returns the original value. Hence, it returns the
tempcopy.