0

I'm new to c++, and I'm struggling to understand the use of private and protected. For example, I have a method where I store a hash variable for a current chess position. I could make the hash variable private or protected, and then have a public function that returns the hash, but why not make the hash variable public so everyone can access it? I get that it means any code outside the class can change the hash and ruin the program, but why would that ever happen? Is making a public variable less efficient or uses more memory?

BanjoMan
  • 120
  • 1
  • 7
  • It's the same reason why you might want to put your jewelry in a safe, but still be willing to open the safe and give them to someone you trust who wants to take a look and admire it, or maybe add a matching set of jewelry to your collection. You don't want to leave your jewelry in the open, don't you? Otherwise it might get stolen. Or replaced with a white glove bearing the mark of the Phantom. – Sam Varshavchik Apr 15 '22 at 01:23
  • A public variable doesn't cause less efficiency or more memory. It's about encapsulation and information hiding. Protected field and methods can be accessed by its derived class while private field can't. – yo1nk Apr 15 '22 at 01:28
  • You say "I get that it means any code outside the class can change the hash and ruin the program, but why would that ever happen?". Why do you think that would never happen?? Imagine *another programmer* using your class, and - since the hash is readily accessible - changing it. That other programmer may simply not understand the implications of changing the hash. And there are a fair number of programmers who will change the hash *because* they understand the damage it would cause. – Peter Apr 15 '22 at 01:31
  • Is the reason not to make everything public because it's dangerous? – BanjoMan Apr 15 '22 at 01:31
  • The instance doesn't have control of its state if all of its members are `public`. In addition to the outright stupid stuff that can happen that you can minimize by restricting access, you can more easily track what happens to the instance by placing a log message or a breakpoint in a method that changes the instance state. – user4581301 Apr 15 '22 at 01:38

0 Answers0