[comp.lang.c++] overloading new operator in C++

schmidt@blanche.ics.uci.edu (Doug Schmidt) (10/09/88)

Hi,

   Would someone please inform me whether the following code is legal
in C++?  If it is, then is the result defined?  G++ 1.27 performs 20
NOPS for the main for loop.  My basic question is:

``Is is possible to hide the new operator in the same fashion as hiding
  the assignment operator `=' , i.e., making it a compile-time error
  to use new?''

----------------------------------------
#include <stream.h>

class Tree_Node {
public:
   static Tree_Node *Base;

private:

   void * operator new ( long ) {
      return ( Base++ );
   } 

};

main() {
   Tree_Node::Base = new Tree_Node [ 20 ];

   for ( int i = 0; i < 20; i++ ) {
      cout << int ( new Tree_Node ) << "\n";
   }
}
----------------------------------------

thanks for any hints,

   Doug Schmidt

bs@alice.UUCP (Bjarne Stroustrup) (10/10/88)

Doug Schmidt of University of California, Irvine - Dept of ICS writes:

 > Hi,
 > 
 >    Would someone please inform me whether the following code is legal
 > in C++?  If it is, then is the result defined?  G++ 1.27 performs 20
 > NOPS for the main for loop.  My basic question is:
 > 
 > ``Is is possible to hide the new operator in the same fashion as hiding
 >   the assignment operator `=' , i.e., making it a compile-time error
 >   to use new?''

	operator new() obeys the usual hiding rules so using new to create an
	individual object of class X is an error when X::operator new() is
	private. Using a 2.0beta cfront I get

"", line 20: error:  main() cannot access Tree_Node::operator new(): private  member

	Using new to create a vector of X objects is OK, though,
	since X::operator new() is used only for individual objects.

	Had Tree_Node::operator  new() been public Tree_Node::Base would have
	been incremented 20 times.

 > ----------------------------------------
 > #include <stream.h>
 > 
 > class Tree_Node {
 > public:
 >    static Tree_Node *Base;
 > 
 > private:
 > 
 >    void * operator new ( long ) {
 >       return ( Base++ );
 >    } 
 > 
 > };
 > 
 > main() {
 >    Tree_Node::Base = new Tree_Node [ 20 ];
 > 
 >    for ( int i = 0; i < 20; i++ ) {
 >       cout << int ( new Tree_Node ) << "\n";
 >    }
 > }