Saturday, March 15, 2008

Overloading the NEW operator - Part II

The NEW operator has, among many advantages, then ability to be overloaded class-wise. In other words, you can overload the NEW operator on a per-class basis, so that your new operator is specifically tailored to respond to what type of object you are applying the NEW operator to.

So you can overload the NEW operator for each class to perform in special situations like handling the case when memory runs out and so on..

Sample code:

class myClass
{
char abc;
int def;
public:
void *operator new(size_t bytes)
{
.....specific code.......
}

};
class otherClass
{
char a;
int b;
public:
void *operator new(size_t bytes)
{
.....specific code.......
}

};
void main()
{
myClass obj1= new myClass();
otherClass obj2 = new otherClass();
.......................
.......................
}

0 comments: