Using C++___What are the reasons for making something "Public" or "Private" when using Classes. | SoloLearn: Learn to code for FREE!


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


7/24/2020 3:42:15 PM

Raul Sanchez

5 Answers

New Answer


Public and privates are access specifier and is used for encapculation..... And It has huge importance for making windows apps and win32 gui


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, 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.


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.


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.


No problem mate! Enjoy coding!