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 6356 times.
Rating of 2.6 with 5 votes

Consider this code

class Car

int _seats;

// etc... with constructors and stuff

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!