What are the different ways to access private fields of a class from outside that class?

Last updated 21 June 2026

  • Legitimate routes: friend functions/classes, public getters/setters, and the class's own member functions and nested types.

  • Workarounds: explicit template instantiation with pointers-to-members (legal per the standard), #define private public (UB, fragile), or raw offset reads via reinterpret_cast (UB).

  • private is a compile-time guard against accidental access, not a security mechanism.

  • https://dev.to/the_infinity/friends-in-c-4oka
  • https://stackoverflow.com/questions/10602927/c-access-private-members-of-class-from-outside-the-class
  • https://www.geeksforgeeks.org/cpp/how-to-access-private-protected-method-outside-a-class-in-c/
All C++ interview questions