Surendhar Surendhar - 1 month ago 12
C++ Question

Access private field of another object in same class

class Person
{
private BankAccount account;

Person(BankAccount account)
{
this.account = account;
}

public Person someMethod(Person person)
{
//Why accessing private field is possible?

BankAccount a = person.account;
}
}


Please forget about the design. I know that OOP specifies that private objects are private to the class. My question is, why was OOP designed such that private fields have class-level access and not object-level access?

Answer

I am also a bit curious with the answer.

The most satisfying answer that I find is from Artemix in another post here (I'm renaming the AClass with Person class): Why have class-level access modifiers instead of object-level?

The private modifier enforces Encapsulation principle.

The idea is that 'outer world' should not make changes to Person internal processes because Person implementation may change over time (and you would have to change the whole outer world to fix the differences in implementation - which is nearly to impossible).

When instance of Person accesses internals of other Person instance - you can be sure that both instances always know the details of implementation of Person. If the logic of internal to Person processes is changed - all you have to do is change the code of Person.