Friday, January 22, 2010

Operator overloading

C++ supports Polymorphism concept with giving different & sepcial behaviour depending upon the context. Generally, this polymorphic behaviour is at compile time or at runtime.
Function overloading & operator overloading are two compile time polymorphism examples.
For this article, we will get an introduction to Operator overloading.

Opearator Overloading -

The existing supported operators are extended for their functionalities ( behaviour ) by operator overloading. This supports the extensibility concept of C++ which has made it to produce great amount of customised libraries.
Operator overloading adds up to the functionalities of the operator with preserving other features like presedence, number of arguments to be operated & basic functionality etc.


Prototype -

return_type operator op (argument list )
{
...
}
op - the operator to be loaded

The keyword "operator" is used for denoting the function as operator overloading function.
The function can not be static. But it can be made friend function.

Limitations -

There are operators which can not be supported for overloading as an exception -
a. Scope resolution operator (::)
b. size of operator (sizeof())
c. conditional operator (?:)
d. pointer to member variable (.*)

Also, when we make the function as friedn function, it can not overload the following operators -
a. =
b. ()
c. []
d. ->


Usability -
Its used for extensibility, reusability with additional features.

Example -

// code of Test2.hpp file

#include
#include

using namespace std;

template
class MyList : public std::list
{

public:

// Default ctor
MyList ( ) : std::list ( ) { };
MyList (size_t n) : std::list (n) { };
MyList (size_t n, const T& val) : std::list (n, val) { };

// overloading operator "[]" as member function
// returns the ith element from the list
const T& operator [] ( size_t i) const
{
typename std::list::const_iterator c_it=this->begin ( );
typename std::list::const_iterator cv_end=this->end ( );

size_t intCnt = 0;

// loop till ith element
while ( intCnt != i && c_it != cv_end )
{
c_it++ ;
intCnt++;
}

// return the ith element value
return *c_it;
}
};


// code of Test2.cpp file


#include "stdafx.h"
#include "Test2.h"

int main(int argc, char* argv[])
{
// instantiate the class MyList for string type values
MyList obj;
//add values
obj.push_back("Avaneesh");
obj.push_back("Anand");
obj.push_back("Amar");

//get the first element
std::cout< //get the second element
std::cout< //get the third element
std::cout<
return 0;
}

No comments: