I\'m a total newbie with tons of ?\'s in my mind and a lot to experience with C++ yet! There\'s been something which I find really confusing and it\'s the use of public vari
By hiding the variable and adding methods now, the class designer allows for inserting arbitrary code into those methods in the future without breaking tons of code that use the attributes directly.
Also note that providing a lot of accessor/mutator methods is generally a sign that your class design needs another look for possible improvement. Class methods should implement actual logic, not just provide access to each member.
I use public variables only in struct
form. For example, I might have a database table that represents a string->value mapping, where value is a composite data structure. I'd just write a structure and use for example std::map
to represent the database table. I don't need to actually do work on the data, merely be able to look it up and make use of it when required.
As noted in a couple comments, even struct
s can often benefit from judicial use of methods, for example a couple of common constructors to keep the members sanely initialized, a clear function to reuse the structure, etc.