×

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

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

Returning a Function Pointer from a Function in C/C++

Pointers to functions can be used in the C programming language just like standard data pointers such as "int *," "char *," etc. The following is a basic example of a...

3 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

Print Table Using Do while 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...

4 minutes read.

C++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method...

4 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.