Overloading new operator

Hello,


Why new operator function always have the parameter as follows? I tried to change the parameter and return type to some other type, but it gives a compile time error. When we overload other operators, the operator will be always associated with th object of the same type. For example if we are overloading + for the class ABC, the argument will be of type ABC&.

void* operator new(size_t size)


Another doubt is Why the argument is not a function pointer, as the RHS of new during object creation is a constructor?


Also why the return type of operator function is void* and not ABC* ?

Thanks,


Last edited on
closed account (1vRz3TCk)
Why new operator function always have the parameter as follows?

The purpose of operator new is to allocate raw, untyped memory large enough to hold an object of the required type, it would make no sense for it to do anything other than this.

There is sometimes confusion between the new and delete expressions and the library functions that have the same name (operator new, operator delete). unlike other operators, such as operator +, new and delete do not overload the expressions, i.e. they do not redefine the behavior of the new and delete expressions.
It is understandable that this confused you, if after reading CodeMonkey's explanation you need more clarification this might help explain it

http://www.cplusplus.com/reference/std/new/operator%20new/

particularly this section
1
2
3
int * p1 = new int;
// same as:
int * p1 = (int*) operator new (sizeof(int));
Last edited on
unlike other operators, such as operator +, new and delete do not overload the expressions, i.e. they do not redefine the behavior of the new and delete expressions.

That was a great explanation. I understand that as the new and delete operate do not redefine the behavior and the usage, there is no need of an associated object, as it is required in the case of the + operator.

int * p1 = new int;
// same as:
int * p1 = (int*) operator new (sizeof(int));


The example was good. I understand that the above statements are already valid and that is the reason why the operator function is having the prototype void* operator new(size_t size), even though the object creation is like ABC *ptr = new ABC().

One more question, why operator function of overloaded delete is having the prototype void operator delete(void* p) and not void operator delete(ABC* p), if ABC is the class name?
Topic archived. No new replies allowed.