C++ - SPLessons

Encapsulation in C++

Chapter 33

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Encapsulation in C++

Encapsulation in C++

shape Description

Every C++ program is the combination of data and functions. OOPs in C++ is mainly used for hiding data. This can be achieved using Encapsulation. Encapsulation in CPP goes a bit negative to Abstraction i.e.hide complexity.

Encapsulation can be defined as an act of combining properties and methods related to same object.

(Or)

Encapsulation is the definition of class which protectively wraps data and functions into a single unit. It is implemented using access specifiers public, private and protected.

Why Encapsulation?

Object becomes equipped with sufficient information set and set of operations.Any system can be assumed as collection of objects. These objects are capable of interacting with each other using various methods.

shape Syntax

class class_name
{
private:
data_type data;
public:
member_functions;
};

main()
{
classname object1,object2……………;
}

shape More Info

Using Encapsulation in CPP , internal representation of object cannot be seen by the end user. Encapsulation and Data hiding are same. Data hiding refers to hiding of details of class from the user.

As discussed private, public and protected are the access modifiers to make a data encapsulated.In order to work with classes containing access specifiers, a special function called “access function” is used and given below.

shape Example

#include<iostream>
using namespace std;

class square
{
private:
	int side;

public:
     void get()    
     {
      cout <<"Enter value of side :"; cin >> side;
     }
     void Area()    
     {
       cout << "Area of Square is:" << side*side;
     }
};

int main()
{
square Obj;
Obj.get();
Obj.Area();
}

Output

Enter value of side :8
Area of Square is:64

Advantages of Encapsulation

shape Advantages

Summary

shape Key Points

  • Class definition wrapping functions and data into a unit is called as Encapsulation in CPP.
  • Encapsulation in CPP is the complement of Abstraction.
  • Encapsulation is performed using accessing functions called as getc() and setc()

shape Programming
Tips

Using encapsulation, one can easily ping to other data types when needed. It can manipulate itself as per the changes made.