bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
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

This chapter

Overview
17

Lessons

49m

Read time

1. C++ OOP2. C++ Classes and Objects3. C++ Class Methods4. C++ Constructors5. C++ Constructor Overloading6. C++ Access Specifiers7. C++ Encapsulation8. C++ The Friend Keyword9. C++ Inheritance10. C++ Multilevel Inheritance11. C++ Multiple Inheritance12. C++ Inheritance Access13. C++ Polymorphism14. C++ Virtual Functions15. C++ Templates16. C++ Files17. C++ Date and Time

On this page

Real-Life ExampleAccess Private MembersWhy Encapsulation?