1

I wonder how I am able to access the private data of an object which is passed by reference or value? this code works. Why? i need some explanations.

class test_t {
    int data;
public:
    test_t(int val = 1): data(val){}
    test_t& operator=(const test_t &);
};

test_t& test_t::operator=(const test_t & o){
    this->data = o.data;
    return *this;
}
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105

1 Answers1

6

private means that all instances of the test_t class can see each other's private data.

If C++ was to be stricter, and to limit private access to methods within the same instance, it would be effectively saying that the type of *this is "more powerful" than the type of your o reference.

The type of *this is the same (†) as the type of o, i.e. test_t &, and therefore o can do anything that *this can do.

(†) The same type, apart from the addition of const, but that's not important here.

Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88
  • 3
    To put it semantically, `private` means that it's part of the implementation of the class and can only be accessed by the implementation of the class. – David Schwartz Jul 12 '15 at 12:26