C++ examples for Class:Operator Overload
Overload new, new[], delete, and delete[] for the Box class.
#include <iostream> #include <cstdlib> #include <new> using namespace std; class Box {/*from w ww .j a v a 2 s. c om*/ int x, y, z; // 3-D coordinates public: Box() { x = y = z = 0; } Box(int i, int j, int k) { x = i; y = j; z = k; } // Set the coordinates of an object after it is created. void set(int i, int j, int k) { x = i; y = j; z = k; } // Overload new and delete for Box objects. void *operator new(size_t size); void operator delete(void *p); // Overload new[] and delete[] for Box arrays. void *operator new[](size_t size); void operator delete[](void *p); // Let the overloaded inserter be a friend. friend ostream &operator<<(ostream &strm, Box op); }; // The Box inserter is a non-member operator function. ostream &operator<<(ostream &strm, Box op) { strm << op.x << ", " << op.y << ", " << op.z << endl; return strm; } // Overload new for Box. void *Box::operator new(size_t size) { void *p; cout << "Using overloaded new for Box.\n"; p = malloc(size); if(!p) { bad_alloc ba; throw ba; } return p; } // Overload delete for Box. void Box::operator delete(void *p) { cout << "Using overloaded delete for Box.\n"; free(p); } // Overload new[] for Box arrays. void *Box::operator new[](size_t size) { void *p; cout << "Using overloaded new[] for Box.\n"; p = malloc(size); if(!p) { bad_alloc ba; throw ba; } return p; } // Overload delete[] for Box arrays. void Box::operator delete[](void *p) { cout << "Using overloaded delete[] for Box.\n"; free(p); } int main() { Box *p1, *p2; int i; // Allocate a Box object. try { p1 = new Box (10, 20, 30); } catch (bad_alloc xa) { cout << "Allocation error for p1.\n"; return 1; } cout << "Coordinates in the object pointed to by p1: " << *p1; // Free the object. delete p1; cout << endl; // Allocate a Box array. try { p2 = new Box [10]; // allocate an array } catch (bad_alloc xa) { cout << "Allocation error for p2.\n"; return 1; } // Assign coordinates to three of p2's elements. p2[1].set(99, 88, 77); p2[5].set(-1, -2, -3); p2[8].set(56, 47, 19); cout << "Contents of a dynamic Box array:\n"; for(i=0; i<10; i++) cout << p2[i]; // Free the array. delete [] p2; return 0; }