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 !!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment