Private vs. Public data members

Hi everyone,

It seems that there are more or less strict rules about whether to keep data members private or public. I was told that the data should be stricly private in order to protect it from misbeheaving users and provide public functions to access and modify it. I understand why, I see the risks of allowing free access to a class' data. Although, from my very poor experience in programming, I noticed that there are a bunch of ways in which data needs to be accessed and/or modified through non-member functions and other classes, and sometimes the quantity of data represented in a class is large, and providing ways for accessing every part of it seems like an absurd task and a waste of time, since we know that the main purpose of the data is to be changed.

So here are basically my questions: isn't it as risky and error prone to give access to data through functions than through immediate access to the data member itself? Why do we do it? Isn't it much more logical and economical in code to simply access the data member as public?


I would really appreciate to get experienced programmers' opinion if possible

Thanks
isn't it as risky and error prone to give access to data through functions than through immediate access to the data member itself?

Nothing is risk free. As you point out using getters and setters does not guarantee correct access. It does however, make it LESS risky and easier to debug.

1) If you're changing member variables all over your program, it is a nightmare to debug. If a public member gets changed, how do you know where it was changed from? With getters and setters, you can always set a breakpoint on the getter or setter and look at the call stack to see exactly where it was called from.

2) If you make member variables public, you expose users of your class to the implementation of your class. If you change how member variables are stored, every place that those member variables are referenced may possibly need to be changed. If you make public interfaces, you might need to change the interface, but if the member variables are private, they are hidden from the user of your class and a change in representation does not affect the use of your class.

3) The concept of encapsulation is a well accepted method of reducing programming errors. Encapsulation does not mean writing a getter and setter for every member variable.

What you need to consider is what member functions to make public. You should make public functions that retrieve or change the STATE of the object in known ways. In general you will find that is a much smaller set of functions than writing a getter and setter for every member variable.

PLEASE DO NOT POST THE SAME QUESTION MULTIPLE TIMES.
http://www.cplusplus.com/forum/general/197494/#msg947573
Last edited on
Topic archived. No new replies allowed.