c++ - Why can we define private members outside of their class scope -
i thought private members don't exist outside of class scope, can't access them. consider:
#include <iostream> class { private: static const int = 1; }; const int a::a; //access private member outside class scope //the compiler doesn't compain int main () { std::cout << a::a << std::endl; //compile-time error } why permitted? convinience?
it permitted because language standard says so.
the concept of member access control implemented of access specifiers private has absolutely nothing imposing restrictions on member definitions. introduced different purposes. intended restrict access in different contexts. language specification not prohibit defining private members outside of class. why it?
your description of private members "not existing" outside of class scope incorrect. language standard says explicitly protected , private members of class visible outside of class , found name lookup. access restrictions checked after that.
e.g. in piece of code following
struct s { void foo(long); private: void foo(int); }; int main() { s().foo(1); } the compiler required see private s::foo(int) outside, choose through overload resolution , tell you attempting call private function.
Comments
Post a Comment