Summary: In this tutorial, we will learn with examples of what is encapsulation in C++.

Introduction to Encapsulation

Encapsulation is one of the important properties of an object-oriented programming language and is defined as wrapping up data and functions into a single unit (e.g. class).

For example, when we create a class and declare variables and functions inside it, we are basically binding them together with the help of the class, thus implementing encapsulation.

But creating a class with properties (attributes) and behaviors (methods) does not always implement encapsulation.

The core concept of encapsulation in OOP is to hide the state (attributes) of an object or class from the outside so that our application is secure and modularised.

How Exactly can we Implement Encapsulation in OOP?

To implement Encapsulation, we restrict the accessibility of the attributes and make the attributes and functions work together.

One of its most implemented example is the getter and setter of a variable.

We create a private variable and write a getter and setter function for it. In doing so no other class can directly access the variable from outside and it can only be done through getter and setter.

That’s why it is said that encapsulation in a way implements abstraction.

Example of Encapsulation in C++

#include <iostream>
using namespace std;
 
class Math{
private:
    int sum;   //Can't be accessed from the main method.
    
public:
    //setter for sum
    void add(int a, int b){
        this->sum = a + b;
    }
    
    //getter for sum
    int getSum(){
        return this->sum;
    }
};
 
int main()
{
    //Single unit i.e. object of a class
    Math math;
    
    //add two number
    math.add(5,4);
    
    //get the sum using getter method
    cout << "Sum: "<< math.getSum() << endl;
    return 0;
}

Output:

Encapsulation in C++

In this program, the variable sum is private, so we cannot access it directly from the main.

We use the getSum() method to get the addition result of the two numbers.

By creating the class, we have bound the sum to work together with the getSum() method (i.e. wrapping up data and function).

Application of Encapsulation

Encapsulation is the core principle of every app written in any OOP language.

For example, if you are writing a library you would only like to expose functions relevant to users and restrict sensitive data that might hinder the performance of your library.

In this tutorial, we learned with examples of encapsulation in the C++ programming language.

Leave a Reply