C++ Tutorial 13


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

Replies - Page 1

0 Orvin Welchez ·
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 Mathias Frits Rørvik ·
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 ·
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 ·
So it works kind of like a reminder that gives you error when you write somthing that should not have been wrote?
+1 Krootushas Gesu ·

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?



No. He means that public variables and functions can be used in a way they are not meant to be used and cause undefined behavior. To avoid that you can hide sensitive functions and variables inside the class by making them private or protected. And expose functions and variables which can not cause any undefined behavior as public.
1 - 0 of 5
1

C++

64,621 followers

About

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

Links

Moderators

Bucky Roberts
Administrator

Search this forum