c++ – What is the point of getters and setters in C ++ (and not only)?

Question:

I'm new to c ++ and can't figure out what exactly getters and setters are for? Why can't you just make the variables inside the class global and change them directly? Why is it necessary to make a variable private and create functions to modify it or get its value?

Answer:

There are many pluses, and here are some of them:

  • you can selectively give access only to the getter or only to the setter
  • prevent the variable from being changed from the outside (giving a copy of it to the getter)
  • I'm not sure about C, but you can set breakpoints on access methods to find out who is calling from where
  • you can add additional code to getter and setter
    • when setting a value, check its validity (and, for example, throw an exception)
    • when setting a value, initialize some related things
    • get a value not from a variable with a getter, but calculate it
    • log access to getter / setter
    • implement and override getter / setter behavior in child classes

In general, you can do without them, but then the size of the code will grow, more time will be spent on debugging, the compiler will not be able to warn against related errors. And the larger / more complex the project, the more benefits they will bring.

Scroll to Top