Background:
Encapsulation is one of the key principles of OOP that has existed in C++ since its inception. The idea is to restrict access to the internal state of an object by providing only well-thought-out interfaces for interaction. In C++, encapsulation is formalized through the visibility sections of class members: public, protected, private.
Problem:
Without using encapsulation, the internal state of objects can be modified from anywhere in the program, leading to errors, hard-to-debug bugs, and an overall decrease in reliability. Excessive restriction, on the other hand, can complicate maintenance and use of classes.
Solution:
It is essential to clearly separate the class interface (public section) from the implementation (private/protected). Use special methods (getters/setters) for accessing important data. For complex logic, separate the mechanism through additional classes or templates. Use const methods to ensure immutability of state.
Code example:
class Counter { private: int value; public: Counter() : value(0) {} void increment() { ++value; } int get() const { return value; } };
Key features:
Can you access a private member of another object of the same class directly within a method?
Yes, within the methods of the class, you can access the private members of other objects of the same class.
class Example { int val; public: void copyVal(const Example& other) { val = other.val; } // No error! };
Can a friend function access the private members of a class?
Yes, a friend function has full access to the private/protected members of the class.
Can a constructor be private? Why is this needed?
Yes, private constructors are often used in singletons and factory methods to control the creation of class instances.
The BankAccount class contains a public variable balance. Any external code can change the balance directly, making it almost impossible to investigate errors resulting from this.
Pros:
Cons:
The balance variable is hidden, with only protected methods for modifying the balance. Validations are implemented within the class.
Pros:
Cons: