0
Using C++___What are the reasons for making something "Public" or "Private" when using Classes.
I was watching a YouTube video going over classes using C++. And I was introduced briefly about making some parts of your program "public" and "private". What are the reasons for making some parts of your program "private"? When is the best time/practice to use "private" in your code? Is it considered bad practice to leave your entire program "public"?
4 Réponses
+ 1
Making attributes of your class creates safety in your program.
Lets say that u have a class called Person.
Inside Person class, you have variables such as name and age.
If you set your Person variables to public, your main method have the power to modify your Person.name, which is unsafe.
Each class must be the only one who can modify your variables. To prevent this from happening, we set our variables inside the Person class as private to make it invisible in other class. If you want to modify the name and age of the Person class, your Person class must have a getter and setter method which are used to set the name and return the name respectively.
This is method of creating safety is called Encapsulation.
You encapsulate your datas so that the other classes cannot modify your variables.
0
codemonkey
Thank you so much for showing me this link! I got a better understanding from reading this article and the comment section gave great examples.
0
Jay Gilbert Garzon
Thank you so much. Very good example, I got to read more on this topic, and started seeing the many reasons for encapsulation.
0
No problem mate! Enjoy coding!