const Rational & Rational::operator++() //Prefix form
{
numer += denom;
return *this;
}
Rational Rational::operator++(int) //Postfix form
{
Rational tmp = *this;
numer += denom;
return tmp;
}
The code above relates to the implementation of a Rational number class. While the class has a number of operations which have been omitted for brevity, its most important components are two private integer members numer and denom, which denote the numerator and denominator, respectively.
The intent of this code is to overload the prefix and postfix increment operators (++) such that they can be used on Rational types, with the net overall effect being that the rational number represented by a Rational object is incremented by 1 when each of the operators are used on it. Here is what I don't understand:
Firstly, the return type for the first method is a constant reference, yet a dereferenced this object shows up in the return statement (*this), does that not mean that an object instead of a reference is actually returned?
Secondly, in the book "Data Structures and Problem Solving Using C++", where this code comes from, it is mentioned that an anonymous int argument is used to differentiate the type signatures of the prefix and postfix forms. What confuses me is that the return types are also different, why?
Lastly, and most importantly, how can I tell from just looking at the code how the compiler (or runtime, please clarify) would determine which method applies to the prefix form and which to the postfix equivalent?
Edit
This was plain wrong as pointed out in the comments by @PeteBecker. You can't make the method
constbecause then it couldn't update the value. My preference would be to return a non-constreference since the function is notconst, but there are reasons to consider aconstreference as mentioned in the comments.
The first signature should not be
constunless you are going to declare the method const as well. Rational& operator++();
The return statement is going to be exactly the same whether you are returning an object or a reference -- both instances will look like you are returning an object. What actually gets returned depends on the method signature and in this case it is a reference.
The return type for the first method can be a reference to the object because you are incrementing the object first before returning it, i.e. pre-increment.
The return type for the second method has to an object because you need to return the original value before it is incremented, i.e. post-increment.
The syntax is different for each method:
++i; // pre-incrmeent - calls first method
i++; // post-increment - calls second method
See cppreference for more examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With