answersLogoWhite

0

How do you overload new operator?

User Avatar

Anonymous

16y ago
Updated: 8/17/2019

Here's an example of what it would look like to overload new and delete for a particular class. class Myclass { public: void* operator new(size_t); void operator delete(void*); }; Both of them are by default static members and do not maintain a this pointer. Overloading can be used for many purposes. For example, we may need to alter the exception thrown in case of failure--std::bad_alloc--and throw something else: void* Myclass::operator new(size_t size) { void *storage = malloc(size); if(NULL == storage) { throw "allocation fail : no free memory"; } } Usually we do this in a base class in order to have the functionality of the overloaded new in all derived classes. Implicitly the definition of new is included in every file, but in order to use the size_t declaration and other new related types you must include the header .

The new operator can be implemented using malloc or another C function, called realloc, that handles memory allocation: void * realloc ( void * ptr, size_t size ); This can be used to change the size of the allocated block at address ptr with the size given in the second parameter. The address pointed to by ptr can actually be changed and the block moved someplace else, in which case the new address will be the returned value. If realloc fails, like malloc, it returns NULL. But realloc will not free the original memory if your memory allocation request fails. Therefore, when you use realloc, be sure to save the previous pointer value in case allocation fails, so that you do not leak memory.

Note that in general, if you overload new, you will likely need to overload delete, and vice versa, because by changing how you allocate memory, you will typically also change how you free memory.

Operator new is invoked implicitly when new is called; there is no syntax for calling operator new explicitly. #include

#include

#include <new>

using namespace std;

class MyClass {

int x, y;

public:

MyClass() {

x = y = 0;

}

MyClass(int lg, int lt) {

x = lg;

y = lt;

}

void show() {

cout << x << " ";

cout << y << endl;

}

void *operator new(size_t size);

void operator delete(void *p);

void *operator new[](size_t size);

void operator delete[](void *p);

};

// overloaded new operator

void *MyClass::operator new(size_t size)

{

void *p;

cout << "In overloaded new.\n";

p = malloc(size);

if(!p) {

bad_alloc ba;

throw ba;

}

return p;

}

// delete operator overloaded

void MyClass::operator delete(void *p)

{

cout << "In overloaded delete.\n";

free(p);

}

// new operator overloaded for arrays.

void *MyClass::operator new[](size_t size)

{

void *p;

cout << "Using overload new[].\n";

p = malloc(size);

if( !p ) {

bad_alloc ba;

throw ba;

}

return p;

}

// delete operator overloaded for arrays.

void MyClass::operator delete[](void*p)

{

cout << "Freeing array using overloaded delete[]\n";

free(p);

}

int main()

{

MyClass *objectPointer1, *objectPointer2;

int i;

try {

objectPointer1 = new MyClass (10, 20);

} catch (bad_alloc xa) {

cout << "Allocation error for objectPointer1.\n";

return 1;;

}

try {

objectPointer2 = new MyClass [10]; // allocate an array

} catch (bad_alloc xa) {

cout << "Allocation error for objectPointer2.\n";

return 1;;

}

objectPointer1->show();

for( i = 0; i < 10; i++)

objectPointer2[i].show();

delete objectPointer1; // free an object

delete [] objectPointer2; // free an array

return 0;

}

User Avatar

Wiki User

16y ago

What else can I help you with?

Related Questions

Difference between new operator and operator new?

new operator allows to allocate a memory from the heap..... so a new instance of a class is created.......... but operator new is used to overload the (new) operator........ juast like overloading of other operators


What is the operator that cannot be overloaded in c plus plus and java?

conditional operator , size of operator , membership operator and scope resulation operator can not be overload in c++


How can you can create a new operator through operator overloading?

You cannot create any new operators in C++. You can only overload the existing ones (although some, such as sizeof, new and delete cannot be overloaded). The only way to create a new operator is to implement it as a standard function with a named identifier. For instance, sqrt() is the standard library function that provides the square root operator, for which no real operator exists.


How unary minus can be overload in c plus plus?

type operator- ();


What is meant when you say you overload an operator?

All operators are built-in but not all operators can operate upon data types they know absolutely nothing about. There are some exceptions such as the new operator and the sizeof operator -- both will work on any datatype. However, for those that cannot, operator overloads allow you to cater specifically for those types. An operator overload is implemented just as you would overload a function, but it is not a function per se because operators have different calling conventions to functions. It is also important to keep in mind that just because you can overload an operator, it does not mean that you should. Operators should only be overloaded when the overload would allow a user to interact with your data type in an intuitive manner; a manner that is consistent with the operator's intended purpose. So while it can be amusing to overload the plus (+) operator to perform a subtraction (-), it could hardly be called intuitive. The assignment operator is the most overloaded operator of them all. This is because it is extremely useful to be able to copy the members of one object and assign those values to another object of the same type. We can also overload the assignment operator to cater for objects of different types, but such assignments are rarely intuitive. Does it make sense to assign the properties of a banana object to a person object? Probably not. Even if you could find a practical reason for doing so, would it be an intuitive operation? Definitely not. Therefore there's no point in providing an operator to cater for this. To create an operator overload, the declaration will often be placed inside the class it pertains to. However there are exceptions. The output stream insertion operator is a good example of this. The following example demonstrates how we can overload an internal operator (the assignment operator) as well as an external operator (output stream insertion operator). #include&lt;iostream&gt; // required to make use of I/O streams class A { private: unsigned m_data; public: // constructors... A (const unsigned data = 0): m_data (data) {} A (const A&amp; copy): m_data (copy.m_data) {} // accessor function (interface) unsigned get_data() const { return m_data; } // operator overloads... A&amp; operator= (const A&amp; rhs) { m_data = rhs.m_data; } A&amp; operator= (const unsigned rhs) { m_data = rhs; } }; std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const A&amp; a { os &lt;&lt; a.get_data(); return os; } int main() { A a, b; // invoke default constructors a = 42; // call assignment operator overload b = a; // call default assignment operator overload // call insertion operator overload std::cout &lt;&lt; a &lt;&lt; std::endl; std::cout &lt;&lt; b &lt;&lt; std::endl; } Output: 42 42


What is the declaration of the function to overload output operator inside class in c plus plus?

You can't overload the insertion operator (&lt;&lt;) from inside a class because the l-value must be an ostream object, but operator overloads implemented within classes always implicate the class instance itself as being the l-value. You must overload the insertion operator from outside of the class, like so: ostream&amp; operator&lt;&lt;(ostream&amp; lhs, const MyObject&amp; rhs) { lhs &lt;&lt; rhs.get_data(); return( lhs ); }


Is sizeof an operator or function why?

You cannot overload the sizeof() operator because that could introduce uncertainty in its evaluation. The sizeof() operator must always produce an accurate and logically predictable result, thus all user-intervention is completely forbidden.


Why should you have to use comparison operator overloading in pairs in c?

You cannot overload operators in C. This is a C++ thing only.


Write c plus plus code to overload operator to find maximum between two objects?

The only operator you need to overload is the greater-than operator. You can then use the std::max function from the standard template library. #include&lt;iostream&gt; #include&lt;algorithm&gt; // for std::max() class my_object { private: int m_data; public: my_object(int data=0): m_data(data) {} my_object(const my_object&amp; copy): m_data(copy.m_data) {} my_object&amp; operator=(const my_object&amp; other) { m_data = other.m_data; } my_object&amp; operator=(const int) { m_data = int; } // greater-than operator overload: const bool my_object::operator&gt; (const my_object&amp; other) { return this-&gt;m_data &gt; other.m_data; } }; int main() { my_object a = 42; my_object b = 0; my_object c = std::max(a, b); // alternatively: my_object d = a &gt; b ? a : b; } Note that the alternative method shown above is slightly less obvious than calling std::max, but both do exactly the same thing. However, both methods require you to overload the greater-than operator.


What is operator function?

An operator function implements a particular operator symbol. The database server provides special SQL-invoked functions, called operator functions, that implement operators. An operator function processes one to three arguments and returns a value. When an SQL statement contains an operator, the database server automatically invokes the associated operator function. The association between an operator and an operator function is called operator binding. You can overload an operator function to provide the operator for a UDT. The SQL user can then use the operator with the UDT as well as with the built-in data types. When an SQL statement contains an operator, the database server automatically invokes the associated operator function.


What happen when a java keyword new is used in an application?

When the new operator is used, a new object is created, based on the specified class.When the new operator is used, a new object is created, based on the specified class.When the new operator is used, a new object is created, based on the specified class.When the new operator is used, a new object is created, based on the specified class.


Why is it necessary to overload an operator?

The assignment is done explicit without internal operation. Subject to the programming language, explicit assignment operators are needed wherever implicit ones are insufficient. Implicit assignment is typically implemented as a flat copy, while explicit overloading of the assignment operator allows for any other suitable behavior. Consider this example in pseudocode similar to C++: class Demo { int* valuepointer; ... }; Demo a, b; ... b = a; Assigning a to b using implicit assignment means that a.valuepointer and b.valuepointer share the same value. Both a and b can change the pointed-to value, and the either will "see" the change. This is the required behavior in some cases, but often, you'd want to explicitly assign a to b such that each has its own pointer, accessing different copies of the value. This behavior would require an explicit assignment operator (or copy constructor).