Never return a non-const pointer to a data member!

This tip submitted by hussain hani on 2009-08-05 08:26:12. It has been viewed 7592 times.
Rating of 5.2 with 33 votes



Consider this code

class Car
{

private:
int _seats;

// etc... with constructors and stuff

public:
//NEVER DO THIS
int* getSeats() { return &_seats; }
};


If you do this, someone can modify the _seats variable without going through the setter method, which violates encapsulation and might mean that important code that should run when the _seats field is changed doesn't actually run.

If you return the value as a const reference or a const pointer, you avoid this problem:

const int& getSeats() { return _seats; }




More tips

Help your fellow programmers! Add a tip!