
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- What is a Proxy Server?
- What is a Proxy Server in information security?
- What is the use of proxy() object in JavaScript?
- What is proxy design pattern and how to implement it in C#?
- Difference between JDK dynamic proxy and CGLib proxy in Spring
- What are the types of Proxy Server?
- What is the class "class" in Java?
- Proxy vs VPN: What are the main differences?
- jQuery $.proxy() Method
- JavaScript Proxy() Object
- What are the differences between Firewall and Proxy Server?
- Creating a Proxy Webserver in Python
- What is the super class of every class in Java?
- What is Regex class and its class methods in C#?
- What is LabelValue class in JavaTuples?

Advertisements