C++ Tutorial 13

+1 Alekro A · August 15, 2014
I am quite new to this so can somebody explain to me why its not good to write public variables in classes?

Post a Reply


Oldest  Newest  Rating
0 Orvin Welchez · August 15, 2014
I'm also pretty new to this but I'll throw my two cents, I'm assuming that when you make public variables, they can be easily modified pretty much by anything and private are kinda dummy proof and there has to be a more complex way of accessing them, making them more secure.
+1 H. P. Lovecraft · August 15, 2014
Because it is considered good practice, since it hides details from the user (other programmers). You don't want to access the raw data directly.

Let's say you have a Car class, which has a variable "amountOfFuel". A Car can't have a negative amount of fuel. If you would directly access the variable, there would not be any way to check if you would set it to a negative number. 

Instead you write a setAmountofFuel(amount) method, where you internally check if there is something wrong with the input and throw an error.

Makes sense?
0 Alekro A · August 16, 2014
So what you mean is that if you make an bigger application the public functions can mess with main while a private function is more secure?
0 Alekro A · August 16, 2014
So it works kind of like a reminder that gives you error when you write somthing that should not have been wrote?
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator