What is encapsulation in C++?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

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:

  1. 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.
  2. Modularity: Encapsulation promotes modularity, as each class can be independently developed and tested.
  3. Security: By restricting access to the internal details of an object, encapsulation helps prevent unintended interference with its state.
  4. 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:

TAGS
Coding Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Does coding pay well?
How to ace coding interviews with arrays and linked lists?
What is basic of testing?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Image
Grokking Data Structures & Algorithms for Coding Interviews
Image
Grokking Advanced Coding Patterns for Interviews
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.