What is Proxy Class in C++?


Here we will see what is the proxy class in C++. The Proxy class is basically the Proxy design pattern. In this pattern an object provides a modified interface for another class. Let us see one example.

In this example, we want to make an array class, that can store only binary values [0, 1]. This is the first try.

Example Code

class BinArray {
   int arr[10];
   int & operator[](int i) {
      //Put some code here
   }
};

In this code, there is no condition checking. But we want the operator[] to complain if we put something like arr[1] = 98. But this is not possible, because it is checking the index not the value. Now we will try to solve this using proxy pattern.

Example Code

#include <iostream>
using namespace std;
class ProxyPat {
   private:
      int * my_ptr;
   public:
      ProxyPat(int& r) : my_ptr(&r) {
      }
      void operator = (int n) {
         if (n > 1) {
            throw "This is not a binary digit";
         }
         *my_ptr = n;
      }
};
class BinaryArray {
   private:
      int binArray[10];
   public:
      ProxyPat operator[](int i) {
         return ProxyPat(binArray[i]);
      }
      int item_at_pos(int i) {
         return binArray[i];
      }
};
int main() {
   BinaryArray a;
   try {
      a[0] = 1; // No exception
      cout << a.item_at_pos(0) << endl;
   }
   catch (const char * e) {
      cout << e << endl;
   }
   try {
      a[1] = 98; // Throws exception
      cout << a.item_at_pos(1) << endl;
   }
   catch (const char * e) {
      cout << e << endl;
   }
}

Output

1
This is not a binary digit

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements