You are on page 1of 2

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.

You might also like