From http://www.learncpp.com/cpp-tutorial/97-overloading-the-increment-and-decrement-operators/
Class declaration
class Digit
{
private:
int m_nDigit;
public:
Digit(int nDigit=0)
{
m_nDigit = nDigit;
}
Digit& operator++();
Digit& operator--();
int GetDigit() const { return m_nDigit; }
};
Their implementation of operator++
Digit& Digit::operator++()
{
// If our number is already at 9, wrap around to 0
if (m_nDigit == 9)
m_nDigit = 0;
// otherwise just increment to next number
else
++m_nDigit;
return *this;
}
My alternate implementation of operator++
Digit& Digit::operator++()
{
return Digit(m_nDigit == 9 ? 0 : (m_nDigit + 1));
}
I wanted to know
- if there are any downsides of creating a new object like I have done, and
- about how to choose one of these implementations?
In your alternative implementation you have 2 issues:
instead of
m_nDigit = 9dom_nDigit == 9. Currentlym_nDigitwill always be 9, and the return value will always be 0.you’re supposed to change the value of
m_nDigit. When returning 0 – you don’t.The return statement is problematic because the operator is expected to change the value of the operand, not to create a new object.
edit
To clarify the problem, consider code:
What would you expect
xto be as the result of this code? I would expect it to be 1. Using your operator, it remains unchanged.