🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to C++ Notes
Topic #92

C++ Encapsulation


Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users.

To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class).

If you want others to read or modify the value of a private member, you can provide public get and set methods.


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;
}

Example explained

  • 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

Want to go beyond the notes?

Join CodingNow 2.0's C++ course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

C++ Encapsulation – FAQs

Quick answers about learning C++ Encapsulation in C++.

This free note from CodingNow 2.0 explains C++ Encapsulation in C++ — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every C++ topic on CodingNow 2.0, including C++ Encapsulation, is 100% free with no signup required.
With focused practice, most students grasp C++ Encapsulation in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now