Borland Online And The Cobb Group Present:


May, 1995 - Vol. 2 No. 5

What's new()?

If you're not familiar with overloading operator new( ), there are actually two different forms that you can overload and two different scopes in which you can declare them. In the accompanying article, Advanced C++ programming - Reconstructing objects, we've described creating the placement syntax version of new( ). However, you can also create your own version of the global operator new( ) operator.

Creating your own global new( ) isn't quite as simple as overloading a normal function. One com-plication is that you don't have access to the original version of new( ) once you've created your own. Instead, you can use the malloc( ) library function to perform the allocation inside your version of new( ), as shown in Figure A. (By the way, if you create your own operator new( ) and use the malloc( ) function to allocate memory, you'll want to create your own operator delete( ) that calls free( ).)


Figure A If you create your own version of new( ), you'll need to allocate memory explicitly.

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

In addition to creating your own version of the global operator new( ), you can create a version that's specific to a class by treating new( ) as if it were a member function of the class. This allows you to customize the behavior of new( ) (and, of course, delete( )) on a class-by-class basis.

As with the global operator new( ), you can create a placement syntax version of new( ) for a class. And just like a class-specific operator new( ), a class-specific placement version limits the scope of the operator to that class.

Return to the Borland C++ Developer's Journal index

Subscribe to the Borland C++ Developer's Journal


Copyright (c) 1996 The Cobb Group, a division of Ziff-Davis Publishing Company. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff-Davis Publishing Company is prohibited. The Cobb Group and The Cobb Group logo are trademarks of Ziff-Davis Publishing Company.