2

To my understanding, new operator calls operator new (which works like malloc) and then calls the constructor for the object (defined in it's class). So as going by the name operator new is also an operator.

If yes, then how can the number of operands be changed when operator new is redefined(overloading the operator). Changing of the number of operands for an operator is not allowed in c++ (as far as my knowledge goes). A unary operator can't be changed into binary (like + can't be overloaded as a ternary operator)

basically, how does this work ?(operator new is supposed to be a unary operator as far as my understanding goes, correct me if I am wrong)

void *operator new(size_t size, char c) 
{ 
   void *ptr; 
   ptr = malloc(size); 
   if (ptr!=NULL) 
      *ptr = c; 
   return ptr; 
} 
main() 
{ 
   char *ch = new('#') char; 
} 

P.S If operator new is actually a function then why is it overloaded as an operator ?

  • Unrelated: *which works like malloc* is an oversimplification. `malloc` provides anonymous blocks of storage that the programmer then shapes with a cast. `new` acquires anonymous storage and throws an exception if it cannot. `new` , shapes the storage it receives and ensures it it properly initialized bu calling the datatype's constructor, if any. Trying to use the two interchangeably leads to bugs, some of them very tricky to detect, track and resolve. – user4581301 Aug 29 '19 at 20:26
  • All operators are functions, but that doesn't mean they can be overloaded for intrinsic types. – πάντα ῥεῖ Aug 29 '19 at 20:27
  • `new` is not an operator – `new T` (and its relatives) are indivisible "new-expressions". `operator new` is not an operator either – think of "operator new" as a funky way of spelling something less confusing, like "allocate". It has a strange name because that did not require adding any more reserved words to the language. (The C++ committee prefers overloading the meaning of existing reserved words and symbols over introducing new ones.) – molbdnilo Aug 29 '19 at 23:50

0 Answers0