Encapsulation is one of the key principles of object-oriented programming (OOP), which arose from the need to group data with the functions that process that data and to hide implementation details from the user.
Since the inception of OOP, encapsulation has been aimed at increasing the reliability of programs, reducing errors, and enhancing the maintainability of code. In C++, it is implemented through data hiding and providing an interface for interaction with the object.
Without encapsulation, the internal data and implementation details of a class are accessible for modification from any part of the program. This leads to errors, difficulties in making changes, and poor manageability of the code.
Encapsulation in C++ is achieved using access modifiers (private, protected, public) in classes. Internal class data is declared with private or protected, and access to it is provided through public methods (getters and setters).
Code example:
class Account { private: double balance; public: Account(double initial) : balance(initial) {} double getBalance() const { return balance; } void deposit(double amount) { if (amount > 0) balance += amount; } };
Key features:
Can a protected member be accessed from anywhere in the program where there is an object of the class?
No, protected members are accessible only from the methods of the class itself, friends, and derived classes, but not from other classes or via an external object.
Can a public class member be "encapsulated"?
No, public members are not encapsulated; their purpose is to provide an external interface. Sometimes overly exposed public members violate the principle of encapsulation.
Does the private modifier add code safety at runtime?
No, access modifiers work only at the compiler level and do not prevent access to data in the executable file — but they limit design errors.
A developer made all class variables public for the sake of "ease of business logic".
Pros:
Cons:
Data is declared as private, interaction through getters/setters with mandatory validation.
Pros:
Cons: