+ 4

What is the need of private access specifier ??

I mean ,we can use public access specifier alone,so we can call the data,functions out of class everytime..why using private access specifier which is access only inside the class??

25th May 2017, 5:29 PM
MUʜAMMED ÉȘʟʟYAS
MUʜAMMED ÉȘʟʟYAS - avatar
2 Answers
+ 3
It's part of data hiding concept. You mostly write classes/structs that you and others will use and implementation of functiond and types of data may change. Thus what people usually do if there's a data member that must be exposed to the outside world is : they make the member private and write a getter/setter method for it (pretty much just a return statement but if needed it can be expanded lster). Especially useful in terms of setters. It is just a simple member function which accepts a parameter of the desired data member and sets it's value to match the parameters. Also, this setter can be improved or secured with your own logic (like: if you have a Player object and want to .SetHP above 100 it will eventually set it to 100). It's not mandatory and is purely comlile-time checked so does NOT provides any security runtime BUT helps your fellow programmers.
25th May 2017, 6:53 PM
Norbivar
Norbivar - avatar
+ 1
because you want to hide the data and you can provide functions to reach them outdide from class, but you cant see the field itself
25th May 2017, 6:47 PM
SzabĂł GĂĄbor
SzabĂł GĂĄbor - avatar