EmptyData EmptyData - 1 year ago 71
C++ Question

which new operator will be called new or new[]?

In the below program overloaded

operator new []
is getting called. But if I comment this function then my overloaded
operator new
is getting called. Shouldn't It called
default new []

#include <iostream>
#include <stdlib.h>
using namespace std;

void *operator new (size_t os)
cout<<"size : "<<os<<endl;
void *t;
if (t==NULL)
return (t);

//! Comment This below function
void* operator new[](size_t size){
void* p;
cout << "In overloaded new[]" << endl;
p = malloc(size);
cout << "size :" << size << endl;
return p;

void operator delete(void *ss) {free(ss);}

int main ()
int *t=new int[10];
delete t;

Answer Source

Looking at the reference, we see:

  1. void* operator new ( std::size_t count );
    Called by non-array new-expressions to allocate storage required for a single object. […]

  2. void* operator new[]( std::size_t count );
    Called by the array form of new[]-expressions to allocate all storage required for an array (including possible new-expression overhead). The standard library implementation calls version (1)

Thus, if you overload version (1) but do not overload version (2), your line

int *t = new int[10];

will call the standard library's operator new []. But that, in turn calls operator new(size_t), which you have overloaded.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download