Overloading new operator

i have seen syntax somewhere that they overloaded new operator to initialize the memory that is allocated
for ex.
char*q=new(*)char;

this actually allocate for one char and initialise it to '*' and keeps that address in q.

here my biggest doubt is what is the need to overload new operator in this most general case as syntax of new also supports initialising the memory we allocate
for ex.

char*q=new char(*);
it also does same thing......then why we overload new operator????Generally what are different cases when we have to overload new operator??????
Can please throw some light on placement new method also..???what is its signficance ???is it same as that of new????
I am new to c++.... Please help

thanks
venkata prasad manne
Last edited on
some reasons for overloading the new operator would be to allocate memory from a specific pool or to change default behavior such as throwing an exception when unable to allocate instead of returning NULL.
in general, the expression Type* p = new(arg1, arg2, arg3) Type; will first call operator new(size_t, arg1, arg2, arg3), which will return a pointer, and then it will construct and initialize the object of type Type at that pointer. Likewise, Type* p = new(arg1, arg2, arg3)Type[size]; will call operator new[](size_t, arg1, arg2, arg3)

By default, C++ only gives you three versions of operator new(): operator new(size_t) (regular new), which allocates from the heap, operator new(size_t, nothrow_t), which allocates from heap and returns null on error, and operator new(size_t, void*) (placement new), which does nothing (and the same for array versions), but you're free to replace them or add more operator new and operator new[] with any sets of arguments.

they overloaded new operator to initialize the memory

I think what you're referring to, is something like operator new(size_t, char), which someone wrote to call the regular operator new and then fill the allocated memory with copies of the char provided.

You are correct that regular new allows initialization, so you can call new char('*'), and such operator new overload is redundant. It would not be redundant for arrays: plain new can only zero-fill an array, new char[n]() or, since c++11, initialize it with values known at compile time: new char[n]{'*', '*', '*'}, but if you don't know how many asterisks are going to be needed, you can't use that. Either fill_n(); later on, or, indeed, you can write an operator new[](size_t, char)
Last edited on
Topic archived. No new replies allowed.