In this lesson, you will learn about Encapsulation in C++, its usage, and examples to better understand the topic.
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
marks()
function, which accepts an argument (m).getMarks()
function.main()
function. The object’s get marks() method is then invoked to retrieve the value.marks()
function, we can now set the private attribute’s value to 99Improved 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.