×

C++ Encapsulation

The following two essential components are present in all C++ programmes:

  • Functions are the parts of a programme that perform actions, and they are termed programme statements (code).
  • Program data is the program's information that is influenced by the program's functions.

What do you mean by Encapsulation?

Data encapsulation is the act of combining data with the functions or procedures that operate on it to create a single unit that is shielded from outside intervention and misuse.

This is a crucial notion in object-oriented programming, and it leads to another OOP concept known as "data hiding." Abstraction exposes just the essential information or interfaces to the outside world, whereas encapsulation hides data and its members.

In a sense, abstraction shows the outer world a "abstract image" of the concealed facts. As a result, we've already established that encapsulation and abstraction are mutually exclusive.

C++ Encapsulation

Encapsulation is represented by a class in C++, which has data members and methods that operate on them, as well as access specifiers such as private, public, and protected.

We also know that class members are private by default. We are genuinely establishing encapsulation when we define class members as private and methods to access class members as public. At the same time, we provide the outside world with an abstract view of data in the form of public methods.

C++ Encapsulation

Encapsulation Implementation

Encapsulation is implemented in C++ as a class that encapsulates data and the methods that operate on it. Data is typically designated as private so that it cannot be accessed outside of the class. The public methods or functions are defined and may be accessed using the class's object.

However, we are unable to directly access private members, which is referred to as data masking. Data is secured and can only be accessed by functions of the class in which it is declared when this is done.

For example,

// Example program
#include <iostream>
#include <string>
using namespace std;
//example class to demonstrate encapsulation
class sampleData{
   int num;
   char ch;
   
   public:
   //getter methods to read data values
   int getInt() const{
      return num;
   }
  
   char getCh() const{
      return ch;
   }
   
   //setter methods to set data values
   void setInt(int num) {
      this->num = num;
   }
  
   void setCh(char ch){
      this->ch = ch;
   }
};
int main()
{
   sampleData s;
   s.setInt(100);
   s.setCh('Z');
   cout<<"num = "<<s.getInt()<<endl;
   cout<<"ch = "<<s.getCh();
  
   return 0;
}

Output

num = 100
ch = Z 

We've created a class out of two member variables and the getter and setter methods in the previous example. This is an illustration of encapsulation.

We've defined two variables, num and ch, as private variables, making them inaccessible to the rest of the programme. They are only available to the public functions that we have disclosed. As a result, we have private variables in a class with concealed data members.

Creating a Strategy

Unless we have a specific need to reveal class members, most of us have learned to make them private by default. That is excellent encapsulation.

This is most commonly applied to data members, although it may be applied to any member, including virtual functions.

C++ Encapsulation

Encapsulation vs. Abstraction: What's the Difference?

Abstraction and encapsulation are inextricably linked. Encapsulation supports abstraction by grouping together data and functions that operate on that data.

EncapsulationAbstraction
The data is hidden.Implementation is hidden.
Combines data and procedures in a single package.Provides a user with an abstract interface that only shows them what they need to know.
Helps with abstraction.Assists with code reuse and security.
Access specifiers define access to data members and methods and are implemented as a class.Implemented as an abstract class with non-instantiable interfaces.

Access specifiers' role in encapsulation

As we saw in the last example, access specifiers are crucial in the implementation of encapsulation in C++. The implementation of encapsulation may be broken down into two steps:

  • Using the private access specifiers, the data members should be identified as private.
  • The public access specifier should be used to designate the member function that manipulates the data members.

What is the purpose of encapsulation?

  • Encapsulation in C++ allows us to group together relevant data and methods, making our code clearer and easier to read.
  • It aids in the management of our data members' modifications.

Consider the case when we want a class's length field to be non-negative. We can now make the length variable private and use the logic within the setAge function (). As an example,

class Rectangle {
  private:
    int age;


  public:
    void setLength(int len) {
      if (len >= 0)
        length = len;
    }
};
  • The getter and setter methods provide our class members read-only or write-only access. As an example,
getLength()  // provides read-only access
setLength()  // provides write-only access
  • It aids in the decoupling of system components. We can, for example, divide code into numerous bundles.
    Decoupled components (bundles) can be produced, tested, and debugged separately and simultaneously. And any modifications to one component have no bearing on the other components.
  • Encapsulation can also be used to conceal data. If we alter the length and breadth variables in Example 1 to private or protected, access to these fields is limited.
    They are also kept secret from the upper classes. This is known as data obfuscation.

Conclusion

One of the most significant properties of OOP is encapsulation, which allows us to conceal data. As a result, data is more secure and protected from unwanted usage.

Encapsulation supports abstraction by allowing us to offer only the appropriate interface to the end-user while hiding all other features.


Related Topics

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

How to Reverse a String in C++ using While Loop

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer...

6 minutes read.

SDL library in C++ with Examples

SDL stands for Simple DirectMedia Layer. Using OpenGL and Direct3D, it is a cross-platform development library created to give users low-level access to audio, keyboard, mouse, joystick, and graphics hardware....

3 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 minutes read.

C++ Encapsulation

The following two essential components are present in all C++ programmes: Functions are the parts of a programme that perform actions, and they are termed programme statements (code).Program data is the...

4 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.