TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  OOP#002

Synopsis:A public method must never return a non-const reference or pointer to member data
Language:C++
Severity Level:2
Category:Object Oriented Programming


Description:

This prevents the calling method from being able to manipulate the data member.

Example:

 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 !!

Singleton patterns are an exception to this rule. Well-known examples of other exceptions to this rule are container classes (e.g. std::vector), operator<<, operator= and various Qt methods.



Literature References:
Ellemtel Rule 29