C++ Encapsulation

In this lesson, you will learn about Encapsulation in C++, its usage, and examples to better understand the topic.


What is Encapsulation?

Encapsulation term in OOP means integrating data and functions into a single entity. To access these data members, set the scope of the member function to public and the scope of the data members to private. The data is made inaccessible to the outside world by encapsulation.

It would be best if you designated class variables and properties as private to accomplish this (you cannot access them outside the class). You can make public getter and setter methods if you want others to be able to alter the value of a private member.

C++ Encapsulation Example

#include <iostream>
using namespace std;
class Student {
  private:
    int marks;

  public:
    void setMarks(int m) {
      marks = m;
    }
  int getMarks() {
    return marks;
  }
};

int main() {
  Student obj;
  obj.setMarks(99);
  cout << "Student Marks = " << obj.getMarks();
  return 0;
}

Output

Student Marks = 99
  • Private attributes with limited access include marks.
  • The marks attribute (marks = m) is set using the public set marks() function, which accepts an argument (m).
  • The value of the private marks returned by the public getMarks() function.
  • We create a Student class object in the main() function. The object’s get marks() method is then invoked to retrieve the value.
  • Using the set marks() function, we can now set the private attribute’s value to 99

Why Encapsulation?

Improved data security: Declaring your class attributes as private is regarded as best practice (as often as possible). Because you (or others) can update one portion of the code without impacting other portions, encapsulation ensures better control of your data.