Encapsulation is achieved in C++ through the use of access specifiers: private, public, and protected. By default, class members are private if no access specifier is specified. Typically, data members are declared as private, and member functions are declared as public to provide controlled access to the private data. This restricts direct access to the data from outside the class, ensuring encapsulation.
Here's an example code demonstrating encapsulation in C++:
#include <iostream>
class Rectangle {
private:
double length;
double width;
public:
// Setter methods
void setLength(double len) {
length = len;
}
void setWidth(double wid) {
width = wid;
}
// Getter methods
double getLength() {
return length;
}
double getWidth() {
return width;
}
// Other public methods
double calculateArea() {
return length * width;
}
};
int main() {
Rectangle rect;
// Set the dimensions using the setter methods
rect.setLength(5.0);
rect.setWidth(3.0);
// Access the dimensions using the getter methods
double length = rect.getLength();
double width = rect.getWidth();
std::cout << "Length: " << length << std::endl;
std::cout << "Width: " << width << std::endl;
std::cout << "Area: " << rect.calculateArea() << std::endl;
return 0;
}
In this example, the Rectangle class encapsulates the data members length and width as private. Access to these members is provided through public setter and getter methods. This way, the internal details of the class are hidden, and users can interact with the object using the public interface. The main function demonstrates how to set the dimensions of the rectangle and access its properties using the public methods.