Access control is a fundamental principle of OOP that ensures encapsulation and protection of a class's internal data.
Background of the issue:
Classical C++ supports three access modifiers: public, protected, private. The idea came to protect the internal implementation of the class and separate the interface from the implementation.
Problem:
Without proper access control, users of the class may inadvertently change the internal state of objects or violate class invariants. Poorly designed access complicates code maintenance and scaling.
Solution:
Use modifiers to make a clear distinction between what can be used by the outside world and what is intended only for the internal purposes of the object.
Code example:
class Sample { private: int secret; protected: void setSecret(int s) { secret = s; } public: Sample(int s) : secret(s) {} int getSecret() const { return secret; } };
Key features:
protected (but not to private).Can a friend function or friend class access private members of another class?
Yes, the friend keyword provides full access to the private and protected members of the class. This approach should be used very cautiously to avoid violating encapsulation.
Example:
class PrivData { private: int secret; friend void accessSecret(const PrivData& d); }; void accessSecret(const PrivData& d) { std::cout << d.secret; }
Is it possible to access a private member if you know its name using pointers or type casting?
Yes, through type casting or memory manipulation (for example, "pointer-to-member trick"), but this violates language standards and leads to undefined behavior. This is not recommended.
What happens during inheritance: are private members of the parent class accessible to the child?
No, private members are not accessible directly to the derived class; access is only possible through public/protected accessor methods of the base class.
Negative case
In a large project, all class members were declared public for the sake of rapid prototyping.
Pros:
Cons:
Positive case
Everything is strictly separated by access levels; friend functions are used only for unit testing.
Pros:
Cons: