bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/C++/C++ Classes
C++•C++ Classes

C++ Encapsulation

Real-Life Example

Think of an employee's salary

  • The salary is private - the employee can't change it directly
  • Only their manager can update it or share it when appropriate

Encapsulation works the same way. The data is hidden, and only trusted methods can access or modify it.

Access Private Members

To access a private attribute, use public "get" and "set" methods:

Example

#include <iostream>
using namespace std;
class Employee {
  private: // Private attribute
  int salary;
  public: // Setter
  void setSalary(int s) {
    salary = s;
  }
// Getter int getSalary() {
return salary;
}
};
int
main() {
  Employee myObj;
  myObj.setSalary(50000);
  cout << myObj.getSalary();
  return 0;
}
  • salary is private - it cannot be accessed directly
  • setSalary() sets the value
  • getSalary() returns the value

We use myObj.setSalary(50000) to assign a value, and myObj.getSalary() to print it.

Why Encapsulation?

  • It is considered good practice to declare your class attributes as private (as often as you can). Encapsulation ensures better control of your data, because you (or others) can change one part of the code without affecting other parts
  • Increased security of data

Previous

C++ Access Specifiers

Next

C++ The Friend Keyword