I know that data in a class should be private then use getter and setter to read/modify them. But isn't it very troublesome compare to using student.scores.push_back(100)
directly which saves a member function.
class Student {
public:
void addToScores(int inScore) {
scores.push_back(inScore);
}
private:
vector<int> scores;
}
In short I'm curious what people actually do in practice, always strictly private data with getter and setter?
The purpose of member functions is to expose an interface. There is no need to make getters and setters, or other trivial functions, to simply move the interfaces already implemented by members to an aggregate container object.
If the client of Student
should be allowed to manipulate scores
however they want, you should make scores
a public member and access it the easy way. If it should be a stack with only push
, pop
, and top
, then use the std::stack
interface adaptor. If only push_back
should be allowed, then you might implement addToScores
. But if the only client is you, and you're not worried about other parts of the std::vector
interface being abused, there's really no point in implementing a new interface.
Every interface within a program should be thoughtfully designed. Adding slapdash interfaces as a habit because standard interfaces (including the C++ default assignment operator) are "dangerous" isn't necessarily a good habit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With