Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
76 views
in C Programming by (112k points)
How is encapsulation achieved in C++?

Please log in or register to answer this question.

1 Answer

0 votes
by (112k points)

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.

Related questions

0 votes
1 answer
asked Jun 7, 2023 in C++ by kvdevika (112k points)
0 votes
1 answer
asked Jun 7, 2023 in C++ by kvdevika (112k points)
0 votes
1 answer
asked Jun 7, 2023 in C++ by kvdevika (112k points)
0 votes
2 answers
asked Jun 7, 2023 in C++ by kvdevika (112k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...