Private Versus Public Data Members
◀ Class▶ Const Object and Const Member Function Amazon
I am under the impression that instructors who teach beginner programming courses usually encourage the use of private data members because that way, data are directly accessible in only the class’ member functions, thereby making data access more secure.
In small programs I usually prefer public variables inside a class because simply using the dot notation allows access to a data item of its objects. You do not need to write a separate function called
get_whatever() to get data, nor do you need to write a separate function called
set_whatever() to modify data.
As a rule of thumb you should ALWAYS keep the member data of a class private.
Why should we add an extra level of access to data? This is because doing so separates accessing the data from how the data are actually stored or retrieved.
For example if you have a piece of private data called
profit in a class and you create a public function
get_profit() for others to call, you can implement the logic of
get_profit() any way you want. The notion of profit may be either pre tax or post tax and
get_profit() can implement accordingly.
In the future if you want to change such notion you just need to change the implementation of
get_profit()! The consumer of
get_profit() NEVER needs to know how it’s implemented.
On the other hand, if you want to be absolutely sure that an object is not modified since its declaration you can make the object
const, as we will discuss in the next section.
◀ Class▶ Const Object and Const Member Function