Purpose of Private and Public Access Specifiers, OOP??

Just a general question, relating to theory. I was just wondering, what exactly is the purpose of declaring private data members? What will be the dis-advantage if we declare public data members? What exactly is the concept behind, private and public?
Private data members exist so that the class can have access to them while everything else can't. For instance, a vector has a private data member that stores the size of the vector. If you let this be public, the client could just change this to whatever it wanted, and any functionality that relied on knowing the size would be greatly hindered.

In general, you want most of your data members to be private, and if you want to give the client access to them, you define get/set functions that can test for valid input before changing the value.
I don't know how this will match question you asked but i'll give example.

You are human object; you can make things.
Are you willing to give priviledges to another human object to change your name as they wish?

in OOP "terms":
Human class can be used via another class such as population. Can everyone from population access each individual human properties? (name, age, hair color, eye color, height, weight........)
Last edited on
freddy explained very well, but I can add to it that it is more way of thinking. For example same programming languages do not have private or protected access. They leave the user to choose the right way to use it, but C++ programmers do not trust users, so they do not let user to choose. Because public data members can be potential security risk for hackers or bugs.
It will also be very useful when you write API for other users to use. If you let user to use data member directly you won't be able to change it after you release your API. Because user will use it in his program it it would be hard for him to change.
Topic archived. No new replies allowed.