How to overload new operator?


For a specific class it is a better approach to overload new operator. The new function always returns a void pointer and takes the argument of type size_t. The object of size_t contains size of the object being allocated. Definition of new function which allocates memory for the object of class emp is as follows:

void * operator new ( size_t sz )

{

emp *e = ( emp* ) malloc ( sz ) ;

return e ;

}

Note that, the this pointer does not get passed to the class-specific new function because it gets called before the constructor. Also although new operator is defined in the class for allocating array of objects global operator will be used.

Subscribe / Share

It's very calm over here, why not leave a comment?

Leave a Reply




Categories

Powered by Yahoo! Answers