While creating a Class ,Why is it advised to keep the Data members Private/Protected ; But then we make use of accessors?

I read this in an article for C++ .

Also,How should I get better at GCC C++?


In general it is good practice to use accessor functions to read or write member variables, as otherwise you may change them independently, so doing damage to the consistency of the class. However for coding contests this may not be the best way to write code, as using accessor functions is slower than reading or writing public member variables directly.

Thank You Sir !
@david_s Sir could you please elaborate what do you mean by damaging the consistency of the class?

Accessor functions allows you to do integrity checks. Example: a class contains two integers a,b of which b must always be larger than b (eg ranges). If you would update a to b+1 directly, this wouldn’t satisfy anymore without anyone noticing. With a accessor function you can tell it to throw an error when it notices someone tries to do this.