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