Pages

Saturday, January 2, 2010

Operator new

If you are going to implement new operator for your class you need to remember that:
1. new returns void pointer
2. new takes one parameter of type size_t.
Here is an example:
#include <iostream>
using namespace std;

class Test
{
int x;
int y;

public:
Test() : x(100), y(100)
{
cout << "Test constructor" << endl;
}

void* operator new(size_t size)
{
cout << "Test::operator new" << endl;
Test* p = (Test*)malloc(size);
cout << "size is " << size << endl;
return p;
}

void Out()
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
}
};


int main()
{
Test* test2 = new Test;
test2->Out();
delete test2;
return 0;
}
This program will show that new receives the size of the object as the input parameter. This new function was called before the constructor.

No comments:

Post a Comment