Why Can Objects of the Same Class Access Each Other's Private Data?
In C , objects of the same class can access each other's private data because access control operates on a per-class, not per-object, basis. This means that private data is only inaccessible to objects outside of the class.
For example, consider the following code:
class TrivialClass { public: TrivialClass(const std::string& data) : mData(data) {} const std::string& getData(const TrivialClass& rhs) const { return rhs.mData; } private: std::string mData; }; int main() { TrivialClass a("fish"); TrivialClass b("heads"); std::cout << "b via a = " << a.getData(b) << std::endl; return 0; }
In this code, TrivialClass has a private member variable mData and a public member function getData that returns a reference to mData. When objects a and b are created, they are both able to access each other's private data through the getData function.
This is possible because C 's access control is based on the following rules:
Since mData is a private member, it should only be accessible from within the TrivialClass class. However, because access control is per-class, objects of the same class can still access each other's private members.
This behavior is not present in all programming languages. Some languages, such as Java, have true per-object access control, which means that objects of the same class cannot access each other's private data.
The above is the detailed content of How Can C Objects of the Same Class Access Each Other's Private Member Variables?. For more information, please follow other related articles on the PHP Chinese website!