Why use private variables inside a class? |
You’re not the only one who asks this question. Have you already tried to read some good article on Internet? Perhaps there isn’t a definitive answer, but you should decide according to your specific code.
A property should be private if you don’t want it to be easily modified.
There’s likely to be no reason to make everything private:
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rh-get
C.131: Avoid trivial getters and setters
Reason A trivial getter or setter adds no semantic value; the data item could just as well be public. |
Editors: Bjarne Stroustrup, Herb Sutter
If you look at the example of what are intended to be trivial getters and setters, you can see they let the private property being freely modified by the class user, so there’s no difference between
1 2 3 4 5 6 7
|
class MyClass {
public:
int getMyInt() const { return myint; }
void setMyInt(int myint_arg) { myint = myint_arg; }
private:
int myint {};
};
|
and
1 2 3 4 5
|
class MyClass {
public:
int myint {};
private:
};
|
In both codes you can assign to the variable “myint” all the values you want, with no restriction.
But usually that’s not what you want for pointers. Pointers
- should be guaranteed to point to an available memory area before been assigned any value;
- if you change the value of a pointer (making it point to a different memory area), you often, but not always, want to delete of free() the previous memory area.
So you’re likely to write a method to set them anyway, both if they are public and private. If so, why keeping them freely accessible, increasing the possibilities to make some mistakes?
I’ve thought for a length to sensible examples for helping you to take some decisions on when you want your properties to be private and when public, but I can’t but admit the ones you can easily find yourself on Internet are far better then mine. But, just to keep it easy, you could think about a situation like this:
Let’s assume you have a simple integer property, like the “int myint;” above; but in your program this int must remain inside a range of values, let’s say no less than 0 and no more than 20. If so, wouldn’t it be simpler to manage it by a method which check the boundaries before assigning the new value? Otherwise you’ll be forced to remember this limitation while writing every single function, even if you had to take a few month pause on that code, which would likely cause you to forget everything about it.
And if you write a method to manage it...
I think the most voted answer here
https://stackoverflow.com/questions/6528499/is-it-okay-to-forgo-getters-and-setters-for-simple-classes
can be kept as an acceptable rule of thumb for this problem.