I'm new to c++ and can't figure out what exactly getters and setters are for? Why can't we 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?
There are many advantages and here are some of them:
- you can selectively give access to only a getter or only a setter
- prevent the variable from being changed from outside (by giving the getter a copy of it)
- not sure about C, but you can set breakpoints on access methods to find out who accessed where
- you can add additional code to the getter and setter
- when setting a value, check its validity (and, for example, throw an exception)
- when setting the value, initialize some related stuff
- get a value not from a variable as 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 increase, 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.