Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading