Encapsulation is a principle of object-oriented design that involves hiding the internal workings of an object and providing only the necessary public interface.
Background: Since the inception of OOP, one of the key tasks has been to protect the internal state of objects from inappropriate modification from outside and to ensure strict control over the logic.
Problem: Without encapsulation, all data and methods become accessible to external code, leading to a loss of control over the state of objects and the emergence of elusive bugs.
Solution:
C++ uses three access specifiers: private, protected, public. private restricts access to members outside the class, protected grants access only to derived classes, and public makes members part of the interface.
Code example:
class Stack { private: int *data; int top; public: Stack(); void push(int val); int pop(); };
Key features:
Is it true that private members cannot be changed in any way outside the class?
False. You can use friend functions, friend classes, or unsafe techniques (for example, through pointer casting or undefined behavior).
In what order are the specifiers applied during inheritance (private, protected, public)?
If inheritance is declared as private, all public and protected members of the base class become private members of the derived class.
What are the differences between protected and private inheritance?
In protected inheritance, all public and protected members of the base class become protected members of the derived class; in private inheritance, all become private.
All class members are declared public, any external code can change the structure and violate the invariants of the object.
Pros:
Cons:
Only necessary public methods are used, other data is closed (private), the state is protected.
Pros:
Cons: