Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What Is Encapsulation?
3.
Features of Encapsulation
4.
Data Encapsulation Example
5.
How is Encapsulation in C++ implemented?
5.1.
Access Specifiers
5.1.1.
1. Public
5.1.2.
2. Private
5.1.3.
3. Protected
6.
Implementation of Encapsulation in C++ 
6.1.
C++
7.
Why do we need Encapsulation?
8.
Types of Encapsulation in C++
9.
What Are the Advantages of Encapsulation in C++?
10.
How To Access Private Encapsulated Data in C++
11.
Frequently Asked Questions
11.1.
What is the difference between data abstraction and Encapsulation in C++?
11.2.
Which construct is used to implement Encapsulation in C++?
11.3.
What is real world example of encapsulation in C++?
12.
Conclusion
Last Updated: Apr 22, 2024
Easy

Encapsulation in C++

Author Teesha Goyal
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

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?

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Features of 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.

Data Encapsulation Example

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;
}

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.

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.

 

Also check out this article - Pair in C++

What Are the 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.

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!

Happy Coding!

Previous article
Abstraction
Next article
Four Pillars of Object-Oriented Programming (OOPS)
Live masterclass