When accessing properties from within a class should you use the private member variable, or the public property?
In C++, there are three access specifiers: public - members are accessible from outside the class. private - members cannot be accessed (or viewed) from outside the class. protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes.
Accessing data members and member functions: The data members and member functions of class can be accessed using the dot('. ') operator with the object. For example if the name of object is obj and you want to access the member function with the name printName() then you will have to write obj. printName() .
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
The protected access modifier is accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor.
There actually is an answer to this question, but I believe it is only quite got at by asking another:
Do I get the desired behaviour from utilising the variable, or the property?
Oftentimes a property performs operations on data, meaning you might not get exact same values from one to the other. Generally they do nothing 'expensive', and not to produce side-effects that manifest in other tenuously related elements of the class (properties shouldn't do this,) but one of the benefits of properties is to have a 'mask', so to speak, providing desired getting and setting behaviour which can differ from a direct return or assignment, where variables are the raw, unadulterated data - this is what you'll need to look out for.
For instance, you might find a property for X
never returns null, but the underlying variable can be, and sometimes is null - in this case, your operations might depend on checking for null while the property exposes a 'safe bet' to the outside. So, you must work with the underlying element in this particular case.
Obviously you should strive for some model of consistency in this practice, but the above is the principle, and the practice would mostly be dictated per solution, project, or even class!
If it's something that has a public property that has a setter, I would use that (all else being equal).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With