I wanted to know What is Proxy Class in C++, why it is created and where it is useful.
Thank a lot in advance.
I wanted to know What is Proxy Class in C++, why it is created and where it is useful.
Thank a lot in advance.
Proxy (among many other meanings) is a design pattern -- see wikipedia for excellent coverage (not intensely C++ specific, of course).
A proxy is a class that provides a modified interface to another class. Here is an example - suppose we have an array class that we we only want to be able to contain the binary digist 1 or 0. Here is a first try:
struct array1 {
int mArray[10];
int & operator[]( int i) {
/// what to put here
}
}; `
We want operator[] to complain if we say something like a[1] = 42, but that isn't possible because the operator only sees the index of into the array, not the value being stored.
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 ) {
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.
A proxy class allows you to hide the private data of a class from clients of the class.
Providing clients of your class with a proxy class that knows only the public interface to your class enables the clients to use your class's services without giving the client access to your class's implementation details.