0
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?

  • Stepping back a little ... what is your understanding of the meaning of `private`? – Drew Dormann Aug 04 '22 at 14:17
  • when defining some class we can set "private" variables than cannot be accesed other than by member functions – alexclabaguet03 Aug 04 '22 at 14:19
  • 1
    @alexclabaguet03 -- How would you implement something like a user-defined copy constructor or assignment operator if you couldn't access the member variables of the passed-in object? It's possible, but would get really ugly (and probably slower in performance) with having to provide public "getters" and "setters" for the `private` members. – PaulMcKenzie Aug 04 '22 at 14:23

1 Answers1

2

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185