What is Proxy Class in C++


Question

What is a Proxy Class in C++? Why it is created and where it is useful?

1
42
4/25/2018 5:45:52 AM

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 only want to contain binary digits (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 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.

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.

72
7/11/2019 4:37:43 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon