×
>
<

C++ Programming

C++ Encapsulation | CrackEase

Encapsulation in C++

Encapsulation in C++

Encapsulation groups data (attributes) and functions (methods) that operate on that data into a single unit — typically a class. By using access specifiers (private, protected, public) we can hide internal details and expose a controlled interface. This improves security, maintainability and reduces unintended interference with internal state.

Example

Real-world analogy & departmental example

  • Payroll keeps salary details; HR keeps employee personal info; Finance keeps financial records.
  • Other departments cannot directly access sensitive payroll data — they must request specific information via proper channels.

The same idea applies in code: direct access to sensitive data is prevented; access is provided via controlled functions.

  
#include <iostream>
using namespace std;

class Employee
{
  private:
    // Hidden from outside code
    int salary;

  public:
    // Setter — controls how salary is modified
    void setSalary(int s)
    {
      if (s >= 0)         // simple validation example
        salary = s;
    }

    // Getter — controlled read access
    int getSalary() const
    {
      return salary;
    }
};

int main()
{
  Employee emp;
  emp.setSalary(80000);              // allowed via public method
  cout << "The salary is: " << emp.getSalary() << endl;
  return 0;
}
  

Observations –

  1. salary is declared private so it cannot be accessed or modified directly from outside the class.
  2. Public methods setSalary and getSalary are the only allowed ways to modify or read the salary — enabling validation and encapsulation.
  3. This binding of data and related functions together while hiding implementation details is encapsulation.

Implementation guidelines:

  1. Keep data members private (or protected) by default.
  2. Provide public (or protected) member functions to expose only required functionality.

Footer Content | CrackEase