Search code examples
c++oopmember

Can member functions of an object acces private members of local a object variable of the same nature? And if yes why? (see example...a.x)


float vector3d::scalar(vector3d a){
    return (x*a.x + y*a.y + z*a.z); // here we can acces a.x even if x is a private 
                                    // member of a (vector3d)....my guess as scalar is a 
                                    // member function of vector3d it can acces private 
                                    // members of local vector3d variables
}

here we can acces a.x even if x is a private member of a (vector3d)....my guess as scalar is a member function of vector3d it can acces private members of local vector3d variables?


Solution

  • Yes an instance can access private members of a different instance of same class. From cppreference:

    A private member of a class is only accessible to the members and friends of that class, regardless of whether the members are on the same or different instances: [...]

    Suppose other instances would have no access. Then it would be impossible to copy a private member when there is no getter method, and this would be rather bad.

     struct foo {
         foo& operator=(const foo& other) {
             x = other.x;
             return *this;
         }
         private:
           int x = 0;
     };
    

    Of course you wouldnt write such a operator=, but a compiler generated one will do very much the same.