Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to make data private?

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?

like image 302
Arch1tect Avatar asked Feb 16 '23 20:02

Arch1tect


1 Answers

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.

like image 59
Potatoswatter Avatar answered Feb 19 '23 11:02

Potatoswatter