0

I am trying to understand how exactly c++ class data member access has been restricted/controlled using access specifiers

Prachi
  • 11
  • 1
  • 2
    Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Oct 08 '19 at 17:53
  • Are you trying to understand the principles or how they principles are implemented? – R Sahu Oct 08 '19 at 17:57
  • 2
    Compiler knows the access specifiers of the members that you've declared. Compiler knows where you use those members. If you violate the restrictions, the compiler diagnoses the problem. That is how it works, unless you're asking how compilers are written. – eerorika Oct 08 '19 at 17:59
  • Thanks @eerorika Yes, I was trying to understand from the compiler perspective. – Prachi Oct 08 '19 at 18:03

1 Answers1

1

The compiler reads the file and stores whether each member was declared public, private or protected. That's it.

There is nothing else. The linker doesn't care. It doesn't impact the executable generated. It doesn't prevent people hacking around it.

Side-story: I've seen code of a major corporation (with influence on the C++ committee) containing this pearl:

#define private public

Just before an #include. And guess what? It made the private members accessible as public. So, really, there's no mechanism past just remembering what's written on the source file and complaining if you try to bypass it.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42
  • The behavior of a program that uses that macro is undefined. – Pete Becker Oct 08 '19 at 18:19
  • @PeteBecker Yeah, that's what made it mind boggling that this org would rely on it. For important real-time data processing, at that! But, without making it acceptable, *if* the compiler keeps the members in the declaration order, in practice, it works. It's ugly, it's bad, it smells, but hey, it will work until it breaks badly, at some compiler update. – Jeffrey Oct 08 '19 at 18:44