Overload new, new[], delete, and delete[] for the three_d class. : New Delete « Overload « C++






Overload new, new[], delete, and delete[] for the three_d class.

  
#include <iostream>
#include <cstdlib>
#include <new>

using namespace std;

class three_d {
  int x, y, z; // 3-D coordinates
public:
  three_d() { x = y = z = 0; }
  three_d(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 three_d objects.
  void *operator new(size_t size);
  void operator delete(void *p);

  // Overload new[] and delete[] for three_d arrays.
  void *operator new[](size_t size);
  void operator delete[](void *p);

  // Let the overloaded inserter be a friend.
  friend ostream &operator<<(ostream &strm, three_d op);
};

// The three_d inserter is a non-member operator function.
ostream &operator<<(ostream &strm, three_d op) {
  strm << op.x << ", " << op.y << ", " << op.z << endl;

  return strm;
}

// Overload new for three_d.
void *three_d::operator new(size_t size)
{
  void *p;

  cout << "Using overloaded new for three_d.\n";
  p = malloc(size);
  if(!p) {
    bad_alloc ba;
    throw ba;
  }
  return p;
}

// Overload delete for three_d.
void three_d::operator delete(void *p)
{
  cout << "Using overloaded delete for three_d.\n";
  free(p);
}

// Overload new[] for three_d arrays.
void *three_d::operator new[](size_t size)
{
  void *p;

  cout << "Using overloaded new[] for three_d.\n";
  p =  malloc(size);
  if(!p) {
    bad_alloc ba;
    throw ba;
  }
  return p;
}

// Overload delete[] for three_d arrays.
void three_d::operator delete[](void *p)
{
  cout << "Using overloaded delete[] for three_d.\n";
  free(p);
}

int main()
{
  three_d *p1, *p2;
  int i;

  // Allocate a three_d object.
  try {
    p1 = new three_d (10, 20, 30);
  } catch (bad_alloc xa) {
    cout << "Allocation error for p1.\n";
    return 1;
  }

  delete p1;

  try {
    p2 = new three_d [10]; 
  } catch (bad_alloc xa) {
    cout << "Allocation error for p2.\n";
    return 1;
  }

  // Assign coordinates to three of p2's elements.
  p2[1].set(9, 8, 7);
  p2[5].set(-1, -2, -3);
  p2[8].set(6, 7, 8);

  cout << "Contents of a dynamic three_d array:\n";
  for(i=0; i<10; i++) cout << p2[i];

  delete [] p2;

  return 0;
}
  
    
  








Related examples in the same category

1.Demonstrate overloaded new and delete.Demonstrate overloaded new and delete.
2.Define new.delete/new[]/delete[] operators