Encapsulation in C++

Master one of the fundamental principles of Object-Oriented Programming that helps you build more maintainable and secure code.

Encapsulation in C++

Introduction

C++ is a highly sophisticated language that supports object-oriented programming. This article will teach you how to create Encapsulation in C++.

Let's understand this concept better.

What is Encapsulation?

Data encapsulation is the process of combining data and the functions or methods that operate on that data into an unique unit that is protected from outside interference and misuse.

This is an essential object-oriented programming concept and it leads to yet another OOP concept known as "Data hiding". Encapsulation conceals data and its members, whereas abstraction reveals only the specifics or interfaces required to interact with the outside world.

Encapsulation, in general, is the method of enclosing similar code in a single location. In C++, we can group together data members and functions in a unique class.

Encapsulation Concept

Real Life Example of Encapsulation

Washing Machine Example

The example is about a washing machine and the purpose of the power button:

  • The power button turns the washing machine on in all cases.
  • After the washing machine is turned on, something happens inside that is not visible to the user.
  • The inside features of the washing machine are encapsulated, or hidden, from the user.
  • Encapsulation ensures that the user does not need to know the details of how the machine works, only how to operate it.
  • The washing machine maintains its inner workings while exposing only necessary interfaces (buttons, dials) to the user.

Features of Encapsulation

Protected Access

We cannot immediately access any of the class's functions. To reach that function, we need an object that uses the class's member variables.

Member Variable Usage

Encapsulation is defined as the use of only member variables in a method created within a class.

Data Protection

It aids in the management of data member modification and improves data protection.

Required Implementation

We don't call it encapsulation if we don't create a method within the class that uses the class's member variable.

Learn Encapsulation in C++ Through Video

Watch this informative tutorial to understand encapsulation better!

Crack your next tech interview with confidence!

Access Specifiers in C++

We have the choice in class to make our data public, private, or protected. This can be accomplished using access specifiers such as public, private, and protected. We can modify the access specifier based on our requirements and data. The programmer can limit data visibility by using these access specifiers. That is, a programmer can determine which functions or data should be hidden and which should be displayed to the user.

Access Specifiers in C++

Public

Class members who have been marked as public are accessible to all. The public data members and member functions can be used by other classes and procedures.

Private

Only the specified member functions have access to the private members when a class is marked as private. Private members cannot be accessed outside the class.

Protected

Protected class members can be accessed by any subclass (derived class) of that class, unlike private members which are not inherited.

How Does Encapsulation Work in C++?

Step 1: Make Data Members Private

To begin, make all data members private to prevent direct access from outside the class.

Step 2: Implement Getter & Setter Methods

For each data member, implement getter (gets the value) and setter (sets the value) methods to provide controlled access.

Implementation of Encapsulation in C++

Encapsulation in C++ is done as a class that groups together data and the functions that operate on it. Most material is declared private so that it cannot be accessed outside of the class. The methods or functions are marked public and can be accessed through the class object.

We cannot, however, immediately access private members, which is known as data hiding. When this is done, the data is secured and can only be viewed by functions of the class in which it is declared.

Example 1: Rectangle Area Calculation
#include <iostream> using namespace std; class Rectangle { public: // Variables required for area calculation int length; int breadth; // Constructor to initialize variables Rectangle(int len, int brth) : length(len), breadth(brth) {} // Function to calculate area int getArea() { return length * breadth; } }; int main() { // Create object of Rectangle class Rectangle rect(20, 10); // Call getArea() function cout << "Area = " << rect.getArea(); return 0; }
Output:
Area = 200
Code Explanation:

In the code above, we are determining a rectangle's area. To compute an area, we need two variables: length and width, as well as a function called getArea(). As a result, we combined these variables and functions into a single class called Rectangle.

Variables and functions in this class can also be obtained from other classes. As a result, this is not data concealment.

Example 2: Employee Salary Calculation
#include <iostream> #include <string> using namespace std; //Accounts class: includes salary info for a particular employee class Accounts{ int empId; double salary, basic, allowances, deductions; public: Accounts(int empId):empId(empId){} //read salary info void readEmployeeInfo(int empId){ cout<<"Enter basic for the employee"<":"; cin>>basic; cout<<"allowances:"; cin>>allowances; cout<<"deductions:"; cin>>deductions; } //calculate salary double calculateSalary(){ salary = basic + allowances - deductions; return salary; } //display details void display(){ salary = calculateSalary(); cout<<"Employee: "<"Salary: "<int main() { Accounts acc(1); acc.readEmployeeInfo(1); acc.display(); }
Output:
Enter basic for the employee1: 10000 allowances: 4324.43 deductions: 1000 Employee: 1 Salary: 13324.4
Code Explanation:

This is a specific example of encapsulation. As shown above, we have a class Accounts that encapsulates account data as well as all functions that act on this data. We can create an object of this class and access functions to get the required information in the main function.

If other classes, such as employee details, want to access account data, it cannot do so immediately. It will need to build an Accounts object and will only be able to access items that are public. Using encapsulation, we can ensure data access management while also ensuring data integrity.

What is the Main Goal of Encapsulation?

Encapsulation is one of the four OOP fundamentals (object-oriented programming). It is a collection of data and the functions that act on it. It is a method of preventing unauthorised entry to the values or functions of a structured data object contained within a class.

The class frequently includes publicly available methods (known as getters and setters) that other classes can use to retrieve and modify the values of the object.

getLength() // provides read-only access setLength() // provides write-only access

Encapsulation is advantageous for a number of factors, including:

  • External code from another portion of our program does not cause unexpected changes to data in our object.
  • We only need to know the outcome of a technique when we use it; we don't need to know the underlying details or how it is implemented.

Types of Encapsulation in C++

In C++, there are three fundamental types of encapsulation:

Class Encapsulation

In this type of Encapsulation, all classes within a function are marked private. This is a common phenomenon in nested classes.

Member Variable Encapsulation

All data members are designated private. In this form, we use getter and setter methods to get and change items.

Function Encapsulation

Only a subset of member functions are declared private, while the function Object() is declared public.

Difference between Abstraction and Encapsulation

Data Abstraction is a process in which the programmer chooses what data is to be displayed to the public; however, the practical implementation of the Abstraction is nothing more than Encapsulation, which is accomplished through the use of access modifiers. You could say that Encapsulation is the implementation of Abstraction.

Abstraction Encapsulation
Abstraction is a process that includes obtaining information. Encapsulation involves methods of containing information.
Abstraction is a method of masking unwanted data while exposing useful information. Encapsulation is the process of combining code and data into a unified unit to protect data from exterior view.
Abstraction enables you to focus on what the item does rather than how it does it. Encapsulation is the process of concealing the internal details or mechanics of how an item performs a function.
Abstraction is accomplished through the use of generic classes and interfaces. Encapsulation is accomplished through the use of access modifiers (Public, Protected, and Private).

Advantages and Disadvantages of Encapsulation

Advantages

The primary benefit of using Encapsulation is that it hides data from other methods. By making the data private, the data is only used within the class and is not available outside of the class.

Data is protected from unwanted users.

This idea is applicable in the marketing and finance sectors, where security and restricted data access to different departments are in high demand.

Encapsulation assists in the binding of a class's member methods and data.

Encapsulation also assists in the creation of flexible code that is simple to change and manage.

Disadvantages

Outside of the class, private info cannot be accessed.

Increased complexity in designing and implementing encapsulated classes.

Potential performance overhead from using accessor methods.

Conclusion

Encapsulation is one of the most important features of OOP. It enables us to keep knowledge hidden. As a consequence, data is more secure and safe from unauthorised access. Encapsulation promotes abstraction by providing only the necessary interface to the end user while concealing all other features.

Good luck and happy learning!

Frequently Asked Questions (FAQs)

What is a encapsulation in C++?

Encapsulation is a key idea of object-oriented programming (OOP) and refers to the grouping of data and related functions (methods) into a single unit called a class.

It is a system that enables the management, defense, and abstraction of information and behavior within a class, giving users command over data access and manipulation.

Access specifiers, which are keywords that specify the visibility and accessibility of class members (data and methods), are used in C++ to achieve encapsulation. In C++, there are three access specifiers:

1. Public: Accessible from anywhere, including outside the class, are public members. They are directly accessible and programmable by code outside the class.

2. Private: Only the class itself has access to private members. They are not directly accessible or manipulable from outside the class. Typically, sensitive or implementation-specific information is encapsulated in private members to provide data hiding and restrict unwanted access.

3. Protected: Protected users have a higher level of visibility than private users but are otherwise similar to them. They are reachable only from within the class and by derived classes (via inheritance), not from outside the class hierarchy. Within a class hierarchy, protected members are utilized to offer controlled access.

C++ encapsulation advantages robust, modular, and maintainable code. Encapsulation's benefits:

1. Data Hiding and Access Control: Encapsulation hides data by declaring class data members private or protected. An object's internal state is not accessible from outside the class. Public member functions—getters and setters—control and validate data access. Encapsulation safeguards data integrity and avoids tampering by obscuring implementation details. Validation standards and data consistency are enforced.

2. Abstraction and Simplified Interface: Encapsulation facilitates abstraction by providing a simplified and well-defined class interface. The class's public methods provide an interface to its capabilities. Encapsulation simplifies programming by hiding core implementation details. Class users can focus on the interface without worrying about the specifics. Classes with well-defined interfaces can be reused, enabling abstraction.

3. Code Organization and Modularity: Encapsulation improves code organization and modularity. Class encapsulation makes code more modular and manageable. Grouped data members and member functions provide structure. Encapsulation creates reusable, self-contained classes, making code easier to comprehend, maintain, and alter. Distinct classes can handle distinct system functions, supporting separation of responsibilities.

OOP uses abstraction and encapsulation to organize, reuse, and maintain code. They are related, but they have separate responsibilities in OOP, including C++.

Abstraction: Abstraction simplifies complex systems by modeling important aspects and hiding superfluous details. It lets developers model real-world objects and concepts as classes and objects. Abstraction emphasizes important system traits and behaviors while avoiding implementation specifics.

Abstraction highlights:

1. Model Creation: Abstraction requires classifying real-world phenomena. Classes define object attributes and methods.

2. Hiding Implementation Details: Abstraction hides complicated implementation details and exposes just user-relevant features and behaviors. This simplifies item use and understanding, letting users interact without worrying about the complexity.

Encapsulation: Encapsulation bundles characteristics and methods into a class. Class visibility and accessibility enhance data hiding, access control, and integrity.

Encapsulation highlights:

1. Data and Method Bundling: Encapsulation bundles related data and methods into a class, creating a self-contained entity. This simplifies code and organizes data and behaviour.

2. Access Control: Encapsulation controls class member visibility. Private data members restrict outside access, whereas public methods allow controlled access.