简体   繁体   中英

Why can we define private members outside of their class scope

I thought the private members don't even exist outside of the class scope, so we just can't access them. But consider:

#include <iostream>

class A
{
private:
    static const int a = 1;
};

const int A::a; //Access to the private member outside the class scope
                //the compiler doesn't compain

int main ()
{
    std::cout << A::a << std::endl; //compile-time error
}

Why is it permitted? Is it just for convinience?

It is permitted because the language standard says so.

The concept of member access control implemented with the help of access specifiers like private has absolutely nothing to do with imposing restrictions on member definitions. It was introduced for completely different purposes. It is intended to restrict access in completely different contexts. Language specification does not prohibit defining private members outside of the class. Why would it?

Your description of private members as "not even existing" outside of class scope is completely incorrect. The language standard actually says explicitly that protected and private members of the class are perfectly visible from outside of the class and even found by the name lookup . Access restrictions are checked only after that.

Eg in a piece of code like the following

struct S {
    void foo(long);
private:
    void foo(int);
};

int main() {
    S().foo(1);
}

the compiler is required to see the private S::foo(int) from outside, choose it through overload resolution and only then tell you that you are attempting to call a private function.

#include <iostream>

class A
{
private:
    /* an in-class initialization, which is only allowed if the
     * data member is static const and is of integral type.
     */
    static const int a = 1;
};

const int A::a; // a definition, not an "access".
/* The above line will actually incur a "duplicate initialization"
 * compile-time error, because the data member a has already been
 * defined in the class.
 */

int main ()
{
    std::cout << A::a << std::endl; // compile-time error
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM