Home > Net >  Can we access private members of another object within a method of a class?
Can we access private members of another object within a method of a class?

Time:10-26

#include <string>
#include <iostream>
#include <vector>

using namespace std;

class Test {
public:
    int testing() {
        Test t;
        return t.x;
    }
private:
    int x = 0;

};

int main() {
    Test a;
    cout << a.testing() << endl;
}

I did not know I can access the private data member x of the t (the instance of Test that is not this) within the class definition of the Test. Why am I allowed to use t.x in the example code?

CodePudding user response:

Colloquially, C 's private is "class-private" and not "object-private".

Scopes are associated with lexical elements of source code, not with run-time entities per se. Moreover, the compiled code has little to no knowledge of the logical entities in the source it was compiled from. For this reason the accessibility is enforced on the level of lexical scopes only. Within the scope of the class, any object of the class's type can have its private members accessed.

Plus, C wouldn't be able to work as a whole otherwise. A copy constructor or an assignment operator could not be written if the accessibility was checked on a per-object basis. Those operations need to access the members of the source object in order to initialize/overwrite the target object.

  • Related