Search code examples
c++operator-overloadingnew-operator

Does overloading the new operator in C++ redefine the operator?


When overloading the new operator in a global scope in C++, are we just redefining the original functionality? From what I understand operator and function overloading works when the overloads have different signatures, however when overloading new operator using

void* operator new(size_t n){
    return malloc(n);
}

we change the underlying functionality itself and whenever we call new this new overload is called? Does this not violate the idea of overloads having different and unique signatures?

I tried overloading the new array operator with extra parameters and how that works is consistent with my current understanding of operator/function overloads. However overloading the new operator and new array operator with just one parameter is where I'm confused.


Solution

  • operator new is replacable (from cppreference, same link):

    The versions (1-4) are implicitly declared in each translation unit even if the header is not included. Versions (1-8) are replaceable: a user-provided non-member function with the same signature defined anywhere in the program, in any source file, replaces the default version. Its declaration does not need to be visible.

    This is not the usual function overloading. You cannot overload a function with same signature. Overloads must be distinguishable by their arguments. Nevertheless, colloquially one often talks about "overloading the new operator" which is ok in the wider sense of "overloading", but in strict c++ terminology not right.