Search code examples
c++overloadingprivateoperator-keyword

How do i access the private data of an object which is passed by reference to operator= function?


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;
}

Solution

  • 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.