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.

c++ encapsulation

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:
// Setter method to set the name
void setName(string n) {
name = n;
}

// Getter method to get the name
string getName() {
return name;
}

// Setter method to set the age
void setAge(int a) {
age = a;
}

// Getter method to get the age
int getAge() {
return age;
}
};

int main() {
// Create an object of the Person class
Person p;

// Set the name and age using setter methods
p.setName(“John”);
p.setAge(25);

// Get and display the name and age using getter methods
cout << “Name: ” << p.getName() << endl;
cout << “Age: ” << p.getAge() << endl;

return 0;
}

Explanation:

  1. Private Data Members:

    • name and age are private variables. They cannot be accessed directly from outside the Person class.
  2. Public Methods:

    • Setter methods (setName, setAge) allow you to set values for name and age.
    • Getter methods (getName, getAge) allow you to retrieve the values of name and age.
  3. Main Function:

    • A Person object p is created.
    • The setName and setAge methods are used to set the name and age.
    • The getName and getAge methods are used to display the values of name and age.

Output:

Name: John
Age: 25