can you access private member variables across class instances?

后端 未结 2 1809
旧巷少年郎
旧巷少年郎 2020-12-04 02:17

I didn\'t think it was possible, but if you have two instances of the same class, are you allowed to access one\'s private members from the other?

Is this why you ca

2条回答
  •  被撕碎了的回忆
    2020-12-04 03:12

    Access restrictions are a property of the class, not of an instance.

    That's why you can write your usual copy constructor:

    class Foo
    {
         int a; // private!
    public:
        Foo (Foo const & rhs) : a(rhs.a) { } // rhs.a is accessible
    };
    

    This idea is also what fuels the "factory" idiom:

    class Bar
    {
        Bar() { } // private?!
    public:
        static Bar * create() { return new Bar(); } // Bar::Bar() is accessible
    };
    

提交回复
热议问题