Table of Contents
In this tutorial, I will take you through the concepts of Encapsulation in C++. It was designed with a bias toward system programming and embedded, resource-constrained software and large systems, with performance, efficiency¸ and flexibility of use as its design highlights.
C++ has also been found useful in many other contexts, with key strengths being software infrastructure and resource-constrained applications,including desktop applications, servers (e.g. e-commerce, Web search, or SQL servers), and performance-critical applications (e.g. telephone switches or space probes)
Concepts of Encapsulation
Encapsulation is one of the feature of OOPs concept which helps in binding together the data and functions that manipulates those data.
ENCAPSULATION
Example
#include<iostream>
using namespace std;
class Parent{
int x;
public:
void setX(int a){x=a;}
int getX() {return x;}
};
int main()
{
Parent b;
b.setX(10);
cout<<"Value for x is:"<<"\t"<<b.getX();
return 0;
}
Output
Value for x is: 10
Program not an Encapsulation
#include<iostream> using namespace std; class Parent{ public: int x; }; int main() { Parent b; b.x =10; cout<< "Value for x is:"<<"\t"<<b.x; return 0; }
Output
Value for x is: 10
ABSTRACTION
Difference between Encapsulation and Abstraction
in a single unit. Whereas abstraction hides the implementation and expose only the interface to the user.
Example
#include<iostream>
using namespace std;
class Refrigerator{
int total;public:
Refrigerator(int i=0){total = i;}
void increaseTemp(int number) {total+= number;} //interface to outside world
void decreaseTemp(int number) {total-= number;} //interface to outside world
int getTemp () {return total;} //interface to outside world
};
int main()
{
Refrigerator r;
r.increaseTemp(5);
cout<<"Total"<<"\t"<<r. getTemp()<<endl;
r.decreaseTemp(2);
cout<<"Total"<<"\t"<<r. getTemp();
return 0;
}
Output
Total 5 Total 3
Also Read: Constructors in C++
Reference: More on C++