Overloading the new array operator.

New Message Reply Date view Thread view Subject view Author view

Ian Reid (ian++at++electrogig.com)
Wed, 21 Feb 1996 10:50:15 -0800


/*
Has anyone ever successfully overloaded the new [] operator ?

The following code illustrates the problem ( I hope ) :

*/
#include <stdio.h>
#include <malloc.h>

#include <string.h>

#define CLASSNEW

class class1 {
public:
 class1 ();
 ~class1();
 void setp ( void * addr ) { p = addr; };
 void setName ( char * s ) { strcpy ( name, s ); };
 const char * getName () { return name; };
#ifdef CLASSNEW
 void * operator new ( size_t);
 void * operator new ( size_t sz, unsigned int n );
#endif
private :
static char name [ 64 ];
static void *p;
 int i [ 4 ];
};

char class1 :: name [] = "abc";

#ifdef CLASSNEW

void *
class1 :: operator new ( size_t sz )
{
 fprintf ( stderr, "c1 new : sz = %d\n", sz );
 return malloc ( sz );
}

void *
class1 :: operator new ( size_t sz, unsigned int n )
{
 fprintf ( stderr, "c1 new : sz = %d n %d\n", sz, n );
 return :: malloc ( sz * n );
}
#endif

class1 :: class1 ()
{
 fprintf ( stderr, "class1::class1\n");
}

void * operator new ( size_t sz, void * p )
{
 fprintf ( stderr, "newsz %d %x\n", sz, p );
 return malloc ( sz );
}

main()
{
 class class1 * c1, * c2, * c3;
 const char * s;
 fprintf ( stderr, "c1\n");
 c1 = new ( NULL ) class1 [ 8 ];
 fprintf ( stderr, "c2\n");
 c2 = new class1 [ 4 ];
 fprintf ( stderr, "c3\n");
 c3 = new class1;
 printf ( "%s\n", c1 -> getName () );
 s = c1 -> getName ();
 if ( s )
  printf ( "%s\n", s );
}

/*
  The first call to new calls the globally overloaded new, and calls the
  constructor as desired. However, I want this behaviour within my class.
  The second call to new calls the standard new operator.
  The third call to new calls the class-overloaded new.
  Again, in an attempt to make it abundantly clear, I want the second
  call to new to call the class-specific new, NOT the global new.
  Who can help me ?
  As long as I can allocate and construct an array of classes, I'll be
  satisfied.
*/

-- 
Ian Reid
Tel 	: 415-288-9852
Email	: ian++at++electrogig.com

New Message Reply Date view Thread view Subject view Author view

This archive was generated by hypermail 2.0b2 on Mon Aug 10 1998 - 17:52:26 PDT

This message has been cleansed for anti-spam protection. Replace '++at++' in any mail addresses with the '@' symbol.