What is encapsulation in C++?
Encapsulation in C++ is a core principle of Object-Oriented Programming (OOP) that involves bundling the data (variables) and methods (functions) that operate on the data into a single unit called a class. It also restricts direct access to some of an object’s components, which is a way to hide the internal implementation details and only expose necessary aspects of an object to the outside world.
Encapsulation is implemented in C++ using access specifiers:
- private: Members declared as private are accessible only within the class itself and are hidden from external access.
- protected: These members are accessible within the class and its derived classes.
- public: Public members are accessible from outside the class.
Benefits of Encapsulation:
- Data Hiding: Encapsulation ensures that the internal state of an object is hidden from the outside world. Only the relevant methods can be used to access or modify the data.
- Modularity: Encapsulation promotes modularity, as each class can be independently developed and tested.
- Security: By restricting access to the internal details of an object, encapsulation helps prevent unintended interference with its state.
- Maintenance: Since the internal workings of a class are hidden, changes to its implementation do not affect other parts of the code, making it easier to maintain.
Example of Encapsulation in C++:
#include <iostream> using namespace std; class Car { private: int speed; public: // Setter to modify speed void setSpeed(int s) { speed = s; } // Getter to access speed int getSpeed() { return speed; } }; int main() { Car myCar; myCar.setSpeed(100); // Setting speed using setter cout << "Car speed: " << myCar.getSpeed() << endl; // Accessing speed using getter return 0; }
In the example above, the variable speed
is encapsulated within the class Car. It can only be accessed or modified via the setSpeed
and getSpeed
methods, ensuring that the internal state of speed
remains protected from unintended changes or invalid values.
Sources:
GET YOUR FREE
Coding Questions Catalog