bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

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

C++ Encapsulation

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind C++ Encapsulation?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

#___ <iostream>
3Order

Put the learning moves in the order that makes the concept easiest to apply.

- The salary is private - the employee can't change it directly - Only their manager can update it or share it when appropriate
Why Encapsulation?
Access Private Members

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