Search code examples
c++access-modifiers

Private set / get functions -- Why private and how to use?


I've read a lot of guides that explain why I should use "private" and the answer is always "Because we don't want anyone else setting this as something". So, let me ask the following questions:

Assuming that I want to have a variable that is set-once (perhaps something like a character name in a video game, ask once, then it's set, and then you just use the get variable(edit:function) for the rest of the game) how do I handle that one set? How would I handle the get for this as well?

What is the actual advantage of using a private access modifier in this case? If I never prompt the user to enter the name again, and never store information back to class.name shouldn't the data remain safe (moderately, assuming code works as intended) anyways?

I hope someone will help me out with this as the explanations I've googled and seen on here have not quite put my thoughts to rest.

Thanks!


Solution

  • The access specifiers mainly serve to denote the class interface, not to effectively limit the programmer's access or protect things. They serve to prevent accidental hacking.

    If something is set once, then you should try to set it when it is created, and make it const.

    If the interface doesn't need to be especially clear (for example, if few people need to learn it) then it doesn't make sense to spend effort engineering it. Moreover changes that don't make much difference in how the interface is used can be applied later. The exposed variable can be changed to a getter/setter using simple search-and-replace.

    If it were a published binary interface, then you would want to get it right the first time. But you're just talking about the internals of your program.

    And it's fairly unlikely that anyone will reset the player name by accident.