When it makes more sense to return const objects
-
While we've seen a lot of stuff here, I thought I might as well take this opportunity to actually post something that might be of use to fellow programmers. I actually posted this yesterday, but for some reason or the other, it didn't get through into the discussion board. This is a nifty tip I got while reading Effective C++ by Scott Meyers, a really fantastic book-and I'd like to share it with you all. Let's say you're implementing a MyPoint class that has prefix and postfix incrementing: class MyPoint { private: int x; int y; public: MyPoint& operator++(); // prefix MyPoint operator++(int); // postfix }; // Implementation - prefix MyPoint& MyPoint::operator++() { ++x; ++y; return *this; } // Implementation - postfix MyPoint MyPoint::operator++(int) { MyPoint CurrPoint = *this; ++(*this); return CurrPoint; } Now, I am sure the above looks innocent enough, but it has a fatal flaw even experienced programmers fall for. More specifically, the glitch is with postfix operator++(int). Consider the potential disaster: // In main() MyPoint x; x++; // valid x++++; // oops, this is valid too! Another twist here is that though operator++(int) is applied twice to x in the line x++++; x is incremented only once since the second time around operator++(int) is only applied the temporary generated by x++ in x++++. Therefore the original value of x is only incremented once, not twice in x++++ (x.operator++(0).operator++(0);). Hence, even if x++++; were syntactically legal, it wouldn't work. So how do we avoid this? we make operator++(int) return a const object, rather than a non-const one. Here is the revised operator++(int) declaration: // Declaration inside class MyPoint const MyPoint operator++(int); // postfix // Implementation - postfix const MyPoint MyPoint::operator++(int) { MyPoint CurrPoint = *this; ++(*this); return CurrPoint; } The logic here is that when the compiler encounters something like x++++; it cannot proceed, since the first call to operator++(int) would now return a const object and you're then applying another operator++(int) to that value-which cannot happen since operator++(int) is a non-const function (only const member functions can be invoked on const objects). This is one of the times returning a const object really makes sense-when implementing postfix operators!