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"?

24th Jul 2020, 3:42 PM
Raul Sanchez
Raul Sanchez - avatar
5 Answers
+ 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.
24th Jul 2020, 4:22 PM
Jay Gilbert Garzon
Jay Gilbert Garzon - avatar
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.
24th Jul 2020, 8:30 PM
Raul Sanchez
Raul Sanchez - avatar
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.
24th Jul 2020, 8:33 PM
Raul Sanchez
Raul Sanchez - avatar
0
No problem mate! Enjoy coding!
24th Jul 2020, 10:47 PM
Jay Gilbert Garzon
Jay Gilbert Garzon - avatar