In: Computer Science
Write a C++ program to explain the following concepts
1.Data hiding
2.Information hiding
3.Proxy class
(solve fast)
1.Data Hiding:
Data hiding is a process of combining data and functions into a single unit. The ideology behind data hiding is to conceal data within a class, to prevent its direct access from outside the class. It helps programmers to create classes with unique data sets and functions, avoiding unnecessary penetration from other program classes.
Following is prog.to understand data hiding in c++
#include<iostream> using namespace std; class Base{ int num;
public: void read(); void print(); }; void Base :: read(){ cout<<"Enter any Integer value"<<endl; cin>>num; } void Base :: print(){ cout<<"The value is "<<num<<endl; } int main(){ Base obj; obj.read(); obj.print(); return 0; }
××××××××××××××××
Information Hiding:
OOPs principal encapsulation and abstraction are used for information hiding, we also called it as data hiding too.Im providing another code for information hiding as follows
#include <iostream> using namespace std; class Adder { public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; int main() { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total " << a.getTotal() <<endl; return 0; }
Here above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly............
××××××××××××××××××××××××
3.proxy class
A proxy is a class that provides a modified interface to another class......
suppose we have an array class that we only want to contain
binary digits (1 or 0)....
We want operator[] to throw if we say something like a[1] = 42, but
that isn't possible because that operator only sees the index of
the array, not the value being stored.
Now We can solve this using a proxy:
#include <iostream>
using namespace std;
struct aproxy {
aproxy(int& r) : mPtr(&r) {}
void operator = (int n) {
if (n > 1 || n < 0) {
throw "not binary digit";
}
*mPtr = n;
}
int * mPtr;
};
struct array {
int mArray[10];
aproxy operator[](int i) {
return aproxy(mArray[i]);
}
};
int main() {
try {
array a;
a[0] = 1; // ok
a[0] = 42; // throws exception
}
catch (const char * e) {
cout << e << endl;
}
}
The proxy class now does our checking for a binary digit and we
make the array's operator[] return an instance of the proxy which
has limited access to the array's internals....
Hope this help you..all the best