Operator Overloading  «Prev

C++ New Delete Operator - Exercise

Overloading the new and delete operators

Objective: Overload the operators new and delete to allow an object to utilize traditional C free store management.

Background

Traditional C programming uses malloc() to access free store and return a void* pointer to the allocated memory. Memory is deallocated by the stdlib.h function free().

Instructions

Use operator overloading of new and delete to allow a testClass object to utilize C traditional free store management according to the given prototypes.

#include <stdlib.h>    //malloc() and free() defined

class testClass {
public:
   void* operator new(size_t size);
   void  operator delete(void* ptr); 
   testClass(unsigned size) { new(size); }
   ~testClass() { delete(this); }
   .....
};

Note:

When a class overloads operator new(), the global operator is still accessible using the scope resolution operator ::.
These class new() and delete() member functions are always implicitly static. The new() operator is invoked before the object exists and, therefore, cannot have a this pointer yet. The delete() operator is called by the destructor, so the object is already destroyed.
The code for the testClass class is available in a file named testclass.cpp, which can be found in the compressed course download file available on the Resources page.

Paste your code below and click the Submit button when you are ready to submit this exercise.