Learn Encapsulation in C++ with simple examples

Learn Encapsulation in C++ with simple examples

The most common programming paradigm is object-oriented programming (OOP), which is taught as the conventional method to writing code for the majority of a programmer's career. OOP is a fundamental programming paradigm every developer uses at some point in their career.

Object-Oriented Programming (OOP) leverages classes and objects.

It's used to break down a software program into reusable code templates (called classes) that may be used to generate specific instances of entities (objects).

C++ is a popular object-oriented programming language in use today, and that's what will be discussed in this blog.

A class is a generic template that may be used to build more particular, meaningful things. Classes are commonly used to describe large classifications with similar characteristics, such as a Motorcycle or a Dog. The classes have fields or attributes that can represent the characteristics of the object and methods which can invoke certain behavior on the object.. The basis for OOP is modeling the classes based on real-world objects - their properties (as fields) and behavior (as methods).

Individual objects created with this class template shall have values for these attributes, for example:

Real-life example of class: Fruits

Real-life object of the class above: Orange

Its attributes include:

  1. Its shape is spherical in nature
  2. It exhibits an orange color.

Its behavior include:

  1. It is acidic in nature
  2. It is quite juicy in nature

On the other hand, there is procedure-oriented programming (or POP) which is associated with the traditional style. The top-down technique is another name for this method.

In this methodology, a program is split into functions that execute specific tasks in this manner. This method is mostly employed in medium-sized applications. The data is global, and all functions have access to it.

The primary disadvantage of procedural programming is that data is not safe since it is global and accessible to any function. Function calls and go-to statements are used to manage the flow of the program.

Difference between object-oriented programming and procedure-oriented programming languages

Object oriented programming vs procedure oriented programming

If you are unsure about access specifiers in C++, don't worry, because soon we'll get into it in detail in a few moments.

Understanding Encapsulation in C++

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.

Data abstraction is a mechanism for exposing only the interfaces and hiding the implementation details from the user, while data encapsulation is a strategy for packaging data and the functions that use it.

Learn Encapsulation by completing a series of fun activities - Start Now!

How is Encapsulation implemented?

Encapsulation in C++ is implemented using classes and access specifiers. Before we dive into the actual code, let's explore more about access specifiers.

Access Specifiers

Access modifiers are used to perform Data Hiding, an important component of Object-Oriented Programming.

In a class, Access Modifiers or Access Specifiers are used to assign access to the members of the class. That is, it imposes some constraints on class members, preventing them from being directly accessible by external functions.

There are three basic access modifiers in C++, namely:

  1. public

Class members defined as public are accessible to everyone. Other classes and functions can access the data members and member functions defined as public.

The direct member access operator (.) with the object of a class can be used to access the public members of that class from anywhere in the program.

Here's an example to clarify the public access specifier in C++:

Output:

In the above code, the data member side is declared as public so that it is accessible outside the class and thus is allowed access from inside the main() function.

2. private

When a class is deemed private, only the member functions specified inside that class have access to the private class members. No other object or function may access them directly from outside the class.

Only member functions and friend functions have access to a class's private data members.

Here's an example to clarify private access specifier in C++:

Output:

Since we are not permitted to access the private data members of the Square class from outside the class, the preceding code produces a compile-time error.

When trying to access the unauthorized obj.side, however, due to the fact that side is a private data member, a compilation error occurs.

3. protected

When a class is deemed protected, it cannot be accessed from outside the same class without the help of a friend class.

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

Here's an example to clarify protected access specifier in C++:

Output:

Why do we need encapsulation?

One of the foundations of OOP is encapsulation (object-oriented programming). It refers to the combination of data and techniques that operate on it.

Encapsulation is a technique for hiding the values or state of a structured data object within a class, limiting unauthorized access.

To access the values, the class usually provides publicly available methods (so-called getters and setters), which other client classes use to get and alter the values within the object.

Encapsulation is quite useful for many reasons such as follows:

  • External code in a completely separate portion of our application does not modify data inside our object in an unanticipated way.
  • To utilize a method, we just need to know what result it will produce when we use it; we don't need to know anything about the object's internals. We could use another completely different object on the inside and not have to change any code because both objects have the same interface.

Implementation of Encapsulation in C++

Output:

The code above exemplifies the notion of encapsulation.

We have a private data member called 'n' that can't be accessed from the main function but can only be accessed by making an object of the class 'Demo'.

We've also defined a parameterized function that sets 'n' to the value returned by the main() function. A getval() method is also defined, which retrieves the current value of 'n'.

We now create a 'Demo' class object and assign a parameter to it inside the main() function. The parameter value is assigned to 'n' when the parameterized function is called.

Finally, we have a cout statement that invokes the getval() method within main() and prints the value.

Try it yourself

Q1. Given a sample program snippet below:

Which of the following options is best suited to access int s1?

  1. ptr1.s1
  2. obj1.s1
  3. ptr1 -> int
  4. obj1 -> s1

Q2. Do you think global variables violate the concept of encapsulation? If so, what do you think is the reason behind it?

Types of Encapsulation in C++

There are three basic types of encapsulation in C++, namely:

  • Member Variable Encapsulation: In this type of encapsulation, all data members are declared private. We use getter and setter methods to retrieve/modify the objects in this type of encapsulation.
  • Function Encapsulation: In this type of encapsulation, only a subset of the member functions are declared private while the constructor is declared public.
  • Class Encapsulation: In this type of encapsulation, all the classes inside a function are declared private. This is commonly observed in nested classes.

Takeaway

At this point, it would be prudent to go over a few benefits that make encapsulation so appealing in the real world. Some of the most significant advantages that encapsulation offers are:

  1. Encapsulated classes improve code readability and maintainability by drastically decreasing the overall code complexity.
  2. Provides a degree of security by shielding data against unauthorized access.
  3. Access specifiers in C++ help change the scope of our data members and member functions at ease.

There are a lot more pros that encapsulation offers to its users, but it's beyond the scope of this blog.

We hope you enjoyed this awesome introduction to encapsulation and its intriguing aspects in C++. Did we miss out on something important? Let us know in the comments below.

Before you leave..

Check out Crio's learning byte to grasp encapsulation in a hands-on way:

Crio Bytes - OOPs Essentials - Encapsulation
A new requirement was implemented in a well-known online shopping platform (like amazon). That requirement needed changes across different modules. Post that change, we see a bug in the repeated code. In this byte, you will improve the design and fix the issue using encapsulation.

Maybe someone out there really needs this blog, and you might be helping them out by sharing it.

Happy Coding.


Sandipan Das

Written by Sandipan Das

Trying to bring about a difference through words.
You've successfully subscribed to Crio Blog
Great! Next, complete checkout to get full access to all premium content.
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Billing info update failed.