With a private modifier, why can the member in other objects be accessed directly?

前端 未结 4 1977
梦如初夏
梦如初夏 2020-11-28 08:13

I have the following code:

class A 
{
private:
    int x;
public:
    A()
    {
        x = 90;
    }
    A(A a1, A a2)
    {
        a1.x = 10;
        a2.x         


        
4条回答
  •  暖寄归人
    2020-11-28 08:41

    Good question. The point is that protection in C++ is class level, not object level. So a method being invoked on one object can access private members of any other instance of the same class.

    This makes sense if you see the role of protection being to allow encapsulation to ensure that the writer of a class can build a cohesive class, and not have to protect against external code modifying object contents.

    Another thought as to the real "why?". Consider how you write almost any copy constructor; you want access to the original's underlying data structure, not its presented interface.

提交回复
热议问题