C++ Encapsulation
Encapsulation is the concept in object-oriented programming (OOP) where data members (attributes) and functions (methods) are bundled together inside a class. This ensures that data is protected and controlled via specific methods.

In encapsulation, it is indeed common and standard practice to make
- data members (variables) Private
- and the functions (methods) public.
This approach is a key aspect of encapsulation in object-oriented programming (OOP), and it helps in achieving data hiding and controlled access to the data.
Simple Encapsulation Example in C++
| #include <iostream> using namespace std;class Person { private: // Private data members string name; int age; public: // Getter method to get the name // Setter method to set the age // Getter method to get the age int main() { // Set the name and age using setter methods // Get and display the name and age using getter methods return 0; |
Explanation:
-
Private Data Members:
nameandageare private variables. They cannot be accessed directly from outside thePersonclass.
-
Public Methods:
- Setter methods (
setName,setAge) allow you to set values fornameandage. - Getter methods (
getName,getAge) allow you to retrieve the values ofnameandage.
- Setter methods (
-
Main Function:
- A
Personobjectpis created. - The
setNameandsetAgemethods are used to set thenameandage. - The
getNameandgetAgemethods are used to display the values ofnameandage.
- A
Output:
Name: John
Age: 25