Why Can Objects of the Same Class Access Each Other's Private Data?
Consider the following code snippet:
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; };
Strangely, getData() can access the private member mData of another TrivialClass object. Why is this allowed?
Per-Class Access Control
In C , access control is implemented on a per-class basis, not a per-object basis. This means that all objects of the same class have the same access to the class's private members, regardless of their state or any other objects they may interact with.
Compile-Time Implementation
C access control is enforced at compile time, making it impractical to implement per-object control. Per-class control, however, can be implemented efficiently and reliably during compilation.
Protected Access
While access control is typically per-class, the protected access specifier provides a rudimentary form of per-object control. However, this control is limited compared to what would be possible with true per-object access control.
In conclusion, objects of the same class can access each other's private data because C 's access control mechanism operates on a per-class basis. This design decision enables efficient and reliable access control enforcement during compilation.
The above is the detailed content of Why Can One Object Access Another's Private Data in the Same C Class?. For more information, please follow other related articles on the PHP Chinese website!