Tip: When it really makes sense to return const objects
-
Hi there, folks! Looks like technically I'm not the first to post a message here (the Welcome folder has already got a few entries in it!!), but still, here's hoping that this message of mine is the first to actually be of use! Since anything techo is okay here, I thought I'd stick in something that I think is quite useful to all programmers out there-something nifty I read in Effective C++ (by Scott Meyers-if you haven't got this book, hey, what're y'all waiting for!): 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!