I am overloading operator new as below
class A {
public:
void* operator new(size_t) { return (void*) Buf; }
};
I am getting "declaration of operator new as non-function error" when I try to compile. Could someone help me with this?
New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.
The new operator invokes the function operator new . For arrays of any type, and for objects that aren't class , struct , or union types, a global function, ::operator new , is called to allocate storage. Class-type objects can define their own operator new static member function on a per-class basis.
Things to Remember in C++ Operator OverloadingWe do not need to create an operator function. Operator overloading cannot change the precedence and associativity of operators. However, if we want to change the order of evaluation, parentheses should be used. There are 4 operators that cannot be overloaded in C++.
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator. Use the delete[] operator to delete an array allocated by the new operator.
Have you size_t
be defined? You need to include stddef.h
for it. But better you include cstddef
and use std::size_t
.
Your declaration otherwise looks fine, apart from the semantics of always returning Buf
being screwed up. The operator new
should return a buffer of the size specified as the first argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With