0

Lets say I have a class A and I overload operator new in the class.

class A{
    public:
    A();
    void *operator new(size_t size);
    void operator delete(void *p);
}

How would I use this overloaded operator new inside of class A instead of the global new? For example

A::A(){
    ...
    int *temp = new int[10];  //Use overloaded new and not global new
}

I looked around and I don't think I saw a question that addressed this.

Thanks!

Daniel W
  • 3
  • 2
  • [How should I write ISO C++ standard conformant custom new and delete operators?](http://stackoverflow.com/questions/7194127/how-should-i-write-iso-c-standard-conformant-custom-new-and-delete-operators) answers your question. – Alok Save Sep 20 '11 at 07:43

1 Answers1

5

That overloaded version will be used for creating objects of class A and its descendants only - such as when you have new A() in your code. It won't be called for new A[] unless you overload operator new[]() as well.

In order to have your operator new[]() function used when you do new int[] you have to replace global operator new()[] function.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • I know how to use the overloaded new when creating a class A. My question is, if I have a member function in class A that makes a call to new (as shown in my question above), how do I call my overloaded new instead of global new? – Daniel W Sep 20 '11 at 07:49
  • @Daniel W: The answer is "you can't do that". Either you replace global `operator new()[]` or you can change your code and call `operator new()` member function explicitly which will require lots of care - no constructors will be called and you will have to call `operator delete()` member function and destructors explicitly again. – sharptooth Sep 20 '11 at 07:51
  • `int * temp = reinterpret_cast(A::operator new (size*sizeof(int)));` - it is not suggested for real classes, I would use only by built in types. – Naszta Sep 20 '11 at 08:09