开发者

C++ - private data members

开发者 https://www.devze.com 2023-02-08 06:14 出处:网络
If I have a class with private data members, for example, do I say that those data members are not accessi开发者_如何学Goble outside the class or they are not accessible outside the objects of that cl

If I have a class with private data members, for example, do I say that those data members are not accessi开发者_如何学Goble outside the class or they are not accessible outside the objects of that class?

Thanks.


Technically speaking, none of the above. You say, "Only entities that have private access to this class can access these variables."

This includes objects of that type, member functions of that type, friends of that type, member functions of friends of that type...

Actually, technically speaking, objects are incapable of accessing anything since they do not have behavior.


private means that member functions of the class (and any nested types) can access those data members, given any instance of the class.


If it is private, then (emphasis added):

its name can be used only by members and friends of the class in which it is declared.

-- Stroustup's "The C++ Programming Language", and one of the draft standards.

In C++, the data itself can always be accessed by other mechanisms. The goal is to impede accidental access, even if malicious access is still feasible.


They are not accessible outside the class's code (including derived classes); except for entities declared friend. As the class's code (the class member functions) are bound to the class (not the individual object), accessibility is evaluated at the class level.

class Foo
{
private:
    int secret;
    Foo * other;

public:
    explicit Foo(Foo* other_) : other(other_), secret(42) {}
    Foo() : other(0), secret(0) {}

    int Peek(void) { return secret; }
    int neighborPeek(void)
    {
        if (other)
            return other->secret; // this is OK, we're still inside the class
        else
            return -1;
}

int main()
{
    Foo aFoo, bFoo(&aFoo);
    std::cout << bFoo.neighborPeek(); // will dump aFoo's secret.

    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消