Followers

Thursday, November 9, 2023

Data encapsulation in C++

 

Data encapsulation is one of the fundamental principles of object-oriented programming and is often associated with C++. It refers to the bundling of data (attributes or variables) and the methods (functions) that operate on that data into a single unit called a class. Data encapsulation restricts direct access to some of an object's components, providing control over the object's internal state and behavior.

Here's an example of data encapsulation in C++:

cpp
#include <iostream> class Car { private: // Private data members (attributes) std::string make; std::string model; int year; public: // Public member functions (methods) // Getter methods to access private data std::string getMake() const { return make; } std::string getModel() const { return model; } int getYear() const { return year; } // Setter methods to modify private data void setMake(const std::string& newMake) { make = newMake; } void setModel(const std::string& newModel) { model = newModel; } void setYear(int newYear) { if (newYear >= 1886) { year = newYear; } else { std::cout << "Invalid year for a car!" << std::endl; } } }; int main() { Car myCar; myCar.setMake("Toyota"); myCar.setModel("Camry"); myCar.setYear(2022); std::cout << "My car is a " << myCar.getYear() << " " << myCar.getMake() << " " << myCar.getModel() << std::endl; return 0; }

In this example:

  1. 1. We have defined a Car class, which encapsulates data related to a car (make, model, and year). The data members (make, model, and year) are marked as private, meaning they can only be accessed and modified from within the class itself.

  2. 2. We provide public member functions (getters and setters) to access and modify the private data members. The getter methods (getMake, getModel, and getYear) allow external code to retrieve the values of the private attributes, while the setter methods (setMake, setModel, and setYear) allow external code to modify these attributes under controlled conditions.

  3. 3. In the main function, we create a Car object (myCar) and use its setter methods to set the car's make, model, and year. We then use the getter methods to retrieve and display this information.

Data encapsulation is essential in C++ because it provides a level of abstraction and data protection. It allows us to hide the internal implementation details of a class and provides controlled access to the data, ensuring that the data is valid and consistent. This helps maintain the integrity of the object's state and allows for easier maintenance and evolution of the code.

No comments:

Post a Comment