Why should some things be private in class?

Hello everyone!

I have noticed that variables in class are private.
Also some functions and static functions.

The questiion is why?

Puting somethings into private like variable for example, does this affect
compiled program or is it just for programmers themself to avoid accessing them?
Thanks!

Btw: i always make everything public in class so i can access everything everytime.
Last edited on
One of the basic advantage or purpose of the class is that it encapsulates attributes. Making something private restricts the access by class only. That means you cannot directly access and/or modify them but you must use a method defined in the class that is public to access or modify them. That way it is easier to debug if an error occurs in the attributes and you have a million lines of code. If you keep on using class with public attributes and methods then you should better use a struct.
the point of making private section is encapsulation and to prevent other objects changing the state of the object as they wish.

imagine a computer programs where user is able to scramble it's internal functionality at it's will, now what do you think how will this program behave after such actions?

that's why program provides interface, that is, ie. a set of buttons available to the user to interact with the program. what these buttons do internally is private to the program and you can't modify this.

the same applies to classes, public section in the class (it's interface) is what buttons are to the program in above example, private section in the class is what internal functionality is to the program in example above. as simple as it is.

a class object might for example have certain conditions under which it's members can be modified.
but if members are public then these conditions can be bypassed.

trivial example:
in multithreaded program multiple threads need to change the state of member variable, but this requires synchronization. (otherwise you get data race)

so making a public method which would provide synced access to private member by implementing a mutex makes sense.


Last edited on
Topic archived. No new replies allowed.