Tuesday, May 29, 2007

Never return a non-const reference to member data from a public function.

Never return a non-const reference to member data from a public function.
-----------------------------------------------------------------------------
class Account
{
public:
Account( int myMoney ) : moneyAmount( myMoney ) {};
const int& getSafeMoney() const { return moneyAmount; }

int& getRiskyMoney() const { return moneyAmount; } // No!
// ...
private:
int moneyAmount;
};

Account myAcc(10); // I'm a poor lonesome programmer a long way from home

myAcc.getSafeMoney() += 1000000; // Compilation error: assignment to constant

myAcc.getRiskyMoney()
+= 1000000; // myAcc::moneyAmount = 1000010 !!

No comments: