0
#include <iostream>
using std::cout;

class distance {
private :
   int feet;
   int inches;
public :
   void setfeet(int x) { feet = x; }
   int getfeet(void) { return feet; }
   void setinches(int y) { inches = y; }
   int getinches(void) { return inches; }
   distance add(distance temp) {
       distance result(0, 0);
       result.feet = feet + temp.feet;
       result.inches = inches + temp.inches;
       return result;
 }
    distance(int ft, int in) : feet(ft), inches(in) {}

};

int main(void)
{
    distance a(5, 6);
    distance b(3, 4);
    distance sum(a.add(b));
    cout << sum.getfeet() <<"\n";
    cout << sum.getinches() << "\n";
    return 0;

}

In this code sample, I can access private data members of result object which is created inside the method add and I can also access the private data member of object temp which is a parameter in the method add using the dot(.) operator how is that possible?

  • 2
    `private` applies to class as a whole, not to single object (instance of the class). See the linked duplicates. – Yksisarvinen Mar 07 '23 at 14:30
  • 5
    Instances of the same type simply have access to each other's private members. It makes sense when you consider things like copy/move operations. – AndyG Mar 07 '23 at 14:30
  • 1
    A member function of a class is allowed access to the private data members of *all* objects of that class type, not only the `this` that it is called on. – Nate Eldredge Mar 07 '23 at 14:30
  • The intention of the access specifiers (`public`, `protected`, `private`) is to provide encapsulation. It is _not_ for security or privacy. – JohnFilleau Mar 07 '23 at 15:00
  • @AndyG or any binary operator – Caleth Mar 07 '23 at 15:04

0 Answers0