Operator Overloading in C++

Only available on StudyMode
  • Download(s) : 157
  • Published : January 8, 2013
Open Document
Text Preview
OPERATOR OVERLOADING

The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.

type operator operator-symbol ( parameter-list )

Need For Operator Overloading
Most fundamental data types have pre-defined operators associated with them. For example, the C++ data type int, together with the operators +, -, *, and /, provides an implementation of the mathematical concepts of an integer. To make a user-defined data type as natural as a fundamental data type, the user-defined data type must be associated with the appropriate set of operators.

Memory management operators
* new (allocate memory for object)
* new[ ] (allocate memory for array)
* delete (deallocate memory for object)
* delete[ ] (deallocate memory for array)
The memory management operators can be overloaded to customize allocation and deallocation (e.g. to insert pertinent memory headers). They should behave as expected, new should return a pointer to a newly allocated object on the heap, delete should deallocate memory, ignoring a NULL argument. To overload new, several rules must be followed: * new must be a member function

* the return type must be void*
* the first explicit parameter must be a size_t value
To overload delete there are also conditions:
* delete must be a member function (and cannot be virtual) * the return type must be void
* there are only two forms available for the parameter list, and only one of the forms may appear in a class: * void*
* void*, size_t

Program implementing new and delete operator overloading in C++. #include <iostream>
#include <cstdlib>
#include <conio.h>
#include <new>
using namespace std;

class...
tracking img