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

前端 未结 4 1981
梦如初夏
梦如初夏 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:53

    A(A a1, A a2)
    {
        a1.x = 10;
        a2.x = 20;
    }
    

    Now from my understanding, you question is how can a object that invoked the constructor call can access other class member variables ?

    Now, both the constructor and the arguments a1,a2 are class scoped. So, it can access all it's members irrespective of it's access level. This too will also work in the constructor -

    this->x = a1.x; // Notice that "this" members can be accessed too.
                    // How ever both the member variables are different and are part of
                    // different objects.
    

提交回复
热议问题