Demonstrate overloaded new and delete. : New Delete « Overload « C++

Home
C++
1.Bitset
2.Class
3.Console
4.Data Structure
5.Data Type
6.Deque
7.Development
8.File
9.Function
10.Generic
11.Language
12.List
13.Map Multimap
14.Overload
15.Pointer
16.Qt
17.Queue Stack
18.Set Multiset
19.STL Algorithms Binary search
20.STL Algorithms Heap
21.STL Algorithms Helper
22.STL Algorithms Iterator
23.STL Algorithms Merge
24.STL Algorithms Min Max
25.STL Algorithms Modifying sequence operations
26.STL Algorithms Non modifying sequence operations
27.STL Algorithms Sorting
28.STL Basics
29.String
30.Valarray
31.Vector
C / ANSI-C
C Tutorial
C++ Tutorial
Visual C++ .NET
C++ » Overload » New DeleteScreenshots 
Demonstrate overloaded new and delete.
Demonstrate overloaded new and delete.
 


#include <iostream>
#include <new>
#include <cstdlib>
using namespace std;

class MyClass {
  int x, y, z; 
public:
  MyClass() {
    x = y = z = 0;
    cout << "Constructing 0, 0, 0\n";
  }
  MyClass(int i, int j, int k) {
    x = i; 
    y = j; 
    z = k;
    cout << "Constructing " << i << ", ";
    cout << j << ", " << k;
    cout << '\n';
  }
  ~MyClass( ) { 
     cout << "Destructing\n"
  }
  void *operator new(size_t size);
  void *operator new[](size_t size);
  void operator delete(void *p);
  void operator delete[](void *p);
  void show() ;
};

void *MyClass::operator new(size_t size)
{
  void *p;

  cout << "Allocating MyClass object.\n";
  p = malloc(size);

  if(!p) {
    bad_alloc ba;
    throw ba;
  }
  return p;
}

void *MyClass::operator new[](size_t size)
{
  void *p;

  cout << "Allocating array of MyClass objects.\n";

  p = malloc(size);
  if(!p) {
    bad_alloc ba;
    throw ba;
  }
  return p;
}

void MyClass::operator delete(void *p)
{
  cout << "Deleting MyClass object.\n";
  free(p);
}

void MyClass::operator delete[](void *p)
{
  cout << "Deleting array of MyClass objects.\n";
  free(p);
}

void MyClass::show()
{
  cout << x << ", ";
  cout << y << ", ";
  cout << z << endl;
}

int main()
{
  MyClass *objectPointer1, *objectPointer2;

  try {
    objectPointer1 = new MyClass[3];       // allocate array
    objectPointer2 = new MyClass(567)// allocate object
  catch (bad_alloc ba) {
    cout << "Allocation error.\n";
    return 1;
  }

  objectPointer1[1].show();
  objectPointer2->show();

  delete [] objectPointer1; // delete array
  delete objectPointer2;    // delete object

  return 0;
}

           
         
  
Related examples in the same category
1.Define new.delete/new[]/delete[] operators
2.Overload new, new[], delete, and delete[] for the three_d class.
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.