C++ - Encapsulation

Encapsulation is one of the fundamental concepts of object-oriented programming (OOP). It is the practice of bundling data (attributes) and methods (functions) together within a class and controlling the access to them. Encapsulation ensures that the internal implementation details of a class are hidden from outside access, and interactions with the class are performed through a well-defined interface.

In C++, private members of a class are encapsulated and cannot be accessed directly from outside the class. They are only accessible from within the class itself, typically through member functions (methods) that provide controlled access to these private members.

class MyClass {
private:
    int privateData;
public:
    void setPrivateData(int value) {
        privateData = value;
    }
    int getPrivateData() {
        return privateData;
    }
};

In this example, privateData is a private member of the MyClass class. It cannot be accessed directly from outside the class. However, we provide public member functions setPrivateData() and getPrivateData() to interact with the private member.

The setPrivateData() function allows setting the value of privateData, and the getPrivateData() function retrieves the value. These member functions act as an interface to access and manipulate the private member privateData.

int main() {
    MyClass obj;
    obj.setPrivateData(10);      // Set the value of privateData
    int data = obj.getPrivateData();  // Retrieve the value of privateData
    return 0;
}

In the main() function, we create an object of the MyClass class. Using the public member functions setPrivateData() and getPrivateData(), we can set and retrieve the value of the private member privateData, respectively.