Table of contents
1.
Introduction
2.
What Is Encapsulation in C++?
3.
Types of Encapsulation in C++
4.
Features of C++ Encapsulation
5.
Example of Data Encapsulation in C++ 
6.
How is Encapsulation in C++ implemented?
6.1.
Access Specifiers
6.1.1.
1. Public
6.1.2.
2. Private
6.1.3.
3. Protected
7.
Implementation of Encapsulation in C++ 
7.1.
C++
8.
Why do we need Encapsulation?
9.
Advantages of Encapsulation in C++
10.
Disadvantages of Encapsulation in C++
11.
How To Access Private Encapsulated Data in C++
12.
Frequently Asked Questions
12.1.
What is the difference between data abstraction and Encapsulation in C++?
12.2.
Which construct is used to implement Encapsulation in C++?
12.3.
What is real world example of encapsulation in C++?
13.
Conclusion
Last Updated: Dec 14, 2024
Easy

Encapsulation in C++

Author Teesha Goyal
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Encapsulation is a notion in Object-Oriented Programming that binds together data and the functions that handle it, keeping both protected from outside intervention and misuse. The crucial OOP notion of data hiding was born from data encapsulation.

Encapsulation in C++

Classes and objects are used in Object-Oriented Programming (OOP). It's used to decompose a program into reusable code templates (known as classes) that may be used to create specific instances of entities (objects).

What Is Encapsulation in C++?

Encapsulation, to put it simply, is the process of preventing users from having direct access to all of an object's variables' state values by limiting parts of an object's components. It deals with disguising the complexity of the programme. Encapsulation in C++ refers to the grouping of related data and functions into a single entity referred to as a class. We shield the data from change by encapsulating these functions and data. Information or data concealing is another name for this idea. Containers in coding are an example of encapsulation since they combine data and methods into a single package.

Types of Encapsulation in C++

There are three basic types of Encapsulation in C++, as follows:-

  • Member Variable Encapsulation: All data members are declared private in member variable encapsulation. We use getter and setter methods to get and alter items in this type of Encapsulation.
  • Function Encapsulation: Only a subset of member functions are declared private under this type of Encapsulation, whereas the constructor is declared public.
  • Class Encapsulation: All of the classes inside a function are declared private in this type of Encapsulation. In nested classes, this is a regular occurrence.

Features of C++ Encapsulation

Features of encapsulation are the following:

  • It restricts access to and modification of a class's fields and methods by exterior classes.
  • Encapsulation can also be used to achieve data hiding.
  • The decoupling of system parts is beneficial.
  • Encapsulation enables activities to access and change an object's state.

Example of Data Encapsulation in C++ 

Let's look at a real-world scenario to understand better what data encapsulation means.

Assume you're a student who needs to get the answer key to an exam you took last week from your teacher. Without permission, you cannot enter the teacher's cabin and collect the answer key. You must first ask your teacher for permission, and only after which your teacher will personally accompany you to her cabin and hand over the answer key to you.

This process ensures that data is secure and unauthorized individuals cannot be tampered with.

How is Encapsulation in C++ implemented?

Encapsulation in C++ is performed using classes and access specifiers.

Access Specifiers

Data Hiding, an essential element of Object-Oriented Programming, is attained via access modifiers.

Access Modifiers or Access Specifiers are used in a class to assign access to its members. It places restrictions on class members, prohibiting them from being accessed directly by external functions.

In C++, there are three basic access modifiers:

1. Public

Everyone has access to class members who have been designated as public. Other classes and methods can use the public data members and member functions.

Public members or functions of a class can be accessed from anywhere in the program by using the direct member access operator that is the dot operator (.) with the object of that class.

2. Private

When a class is marked as private, only the member functions defined have access to the private members. Private members or functions cannot be accessed outside the class or by any other object or method.

The secret data members of a class are only accessible to member functions and friend functions. The subclass of a class does not inherit private members or functions.

3. Protected

When a class is designated as protected, it cannot be accessed without the assistance of a friend class.

The protected class members can be accessed by any subclass (derived class) of that class, which is the main difference between this and the private access specifier.

Implementation of Encapsulation in C++ 

  • C++

C++

#include<iostream>
using namespace std;

class demo {
   private:
       //private member hidden from outside world
       int var;
       
   public:
       //to set the value of var
       void set_var(int temp)
       {
           var =temp;
       }
       
       //to get the value of var
       int get_var()
       {
           return var;
       }
};

// main function
int main() {
   //creating object of demo class
   demo obj;
   
   //using set_var function to set the value 100 to private member var
   obj.set_var(100);
   
   //using get_var function to get/access the value of private member var
   cout<<obj.get_var();
 
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

100


You can practice by yourself with the help of Online C++ Compiler for better understanding

Why do we need Encapsulation?

Encapsulation is one of the four pillars of OOP (object-oriented programming). It refers to a set of data and functions that operate on it. It is a technique for preventing unwanted access to the values or functions of a structured data object within a class.

The class often includes publicly accessible methods (so-called getters and setters) that other classes use to get and change the values within the object.

Encapsulation is beneficial for a variety of reasons, including the following:

  • External code from a different part of our program does not change data in our object in an unexpected way.
  • We only need to know what outcome a method will produce when we use it; we don't need to know the underlying details or implementation of it.

Know What is Object in OOPs here in detail.

Also check out this article - Pair in C++

Advantages of Encapsulation in C++

The advantages of Encapsulation in C++ are:

  • Data Hiding: Protects sensitive data from unauthorized access.
  • Modularity: Encourages modular design by bundling data and methods together.
  • Flexibility: Allows for easy modification of internal implementation without affecting external code.
  • Enhanced Security: Prevents unintended modification of data through encapsulation.
  • Code Reusability: Encapsulated classes can be reused in different parts of the program without modification.

Disadvantages of Encapsulation in C++

  • Increased Complexity: Encapsulation can make the code more complex, especially when there are numerous getter and setter methods to access private data. This can lead to longer and harder-to-maintain code.
  • Performance Overhead: The use of getters and setters for accessing private members can introduce minor performance overhead due to additional method calls, although this is generally negligible unless done in performance-critical applications.
  • Limited Flexibility: Encapsulation can sometimes limit flexibility, as it forces access to class members through methods, even when direct access might be more appropriate in certain situations, such as when performance is a concern.
  • Difficulty in Debugging: Since data is hidden and accessed only through methods, debugging can become more difficult, as it may require stepping through multiple layers of function calls to access or modify data.
  • Code Bloat: In certain scenarios, encapsulation can lead to excessive boilerplate code, such as writing multiple getter and setter methods for every private variable, which can make the code less concise and harder to read.
  • Incompatibility with Low-Level Programming: Encapsulation may not be ideal for low-level programming where direct memory manipulation or performance optimizations are needed, as it restricts direct access to data.

How To Access Private Encapsulated Data in C++

Accessing Private Encapsulated Data in C++ involves using public member functions provided by the class to manipulate private data indirectly. These member functions act as interfaces to access and modify encapsulated data, ensuring data integrity and encapsulation principles. Through encapsulation, the class controls access to its data, preventing unauthorized manipulation. 

By exposing only necessary functionality through public interfaces while hiding implementation details, encapsulation promotes secure and maintainable code. This approach also enables easier debugging and maintenance, as changes to internal implementation do not require modifications to external code that uses the class. Overall, encapsulation is a fundamental principle in C++ programming that enhances code organization, security, and reusability.

Frequently Asked Questions

What is the difference between data abstraction and Encapsulation in C++?

Abstraction is a technique of hiding unnecessary or unwanted information.  In comparison, Encapsulation is the method of wrapping up data in a single unit and also provides a method for protecting the data from the outside.

Which construct is used to implement Encapsulation in C++?

We can use access specifiers to implement Encapsulation. They allow the programmer to choose which data or functions should be exposed to the user and which should be hidden.

What is real world example of encapsulation in C++?

Driving an automobile is one example of encapsulation in the real world. As a driver, you are aware of how to start the vehicle by pressing the start button, and you are unaware of the internal specifics of the beginning processes.

Conclusion

In this article, We discussed Encapsulation in C++. Encapsulation stands as a fundamental principle in C++ programming, enabling developers to create robust, secure, and maintainable code. By bundling data and methods together within classes and controlling access through well-defined interfaces, encapsulation promotes modularity, code reusability, and data integrity.

Recommended Readings:

Are you planning to ace the interviews of reputed product-based companies like Amazon, Google, Microsoft, and more?

Attempt our Online Mock Test Series on Code360 now!

Live masterclass