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.

This entry was posted in C++ and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>