ProgrammingC++ Developer

How does the encapsulation mechanism work in C++ and what are the purposes of the private/protected/public specifiers?

Pass interviews with Hintsage AI assistant

Answer.

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:

  • Access control to class members
  • Explicit separation of interface and implementation
  • Allows modification of internal structure without affecting users

Tricky questions.

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.

Common mistakes and anti-patterns

  • Exposing the entire structure (all public)
  • Storing pointers and exposing their access (violating encapsulation)
  • Hiding the interface together with the implementation (too rigid restrictions)

Real-life example

Negative case

All class members are declared public, any external code can change the structure and violate the invariants of the object.

Pros:

  • Fast prototyping

Cons:

  • No guaranteed correctness; many bugs in large projects

Positive case

Only necessary public methods are used, other data is closed (private), the state is protected.

Pros:

  • Easier code maintenance
  • Minimization of bugs

Cons:

  • Sometimes wrappers (getter/setter) need to be written, which can be excessive for internal purposes