Thursday, July 9, 2009

Operator overloading in C++?

hi everyone..


can you please tell me how to make overloading for the operater =....


and explain if you can...


thanx

Operator overloading in C++?
1- Since it is one of the assignment operators (=, +=, -=, etc.), it MUST be overloaded as a non-static (public) member function in your class, because it will operate on user-defined objects.


2- Considering the above and the fact that it is a binary operator, the assignment operator (=) will be overloaded with one argument.


3- So a call like a = b for example, will be treated as a.operator=(b), where a and b are objects of your class.


4- The following is an INCOMPLETE example from my book.** It is a user-defined "Array" class.


5- Defining a proper COPY CONSTRUCTOR is essential for using the overloaded assignment operator correctly.


6- Notice the use of the ampersand operator (%26amp;) to indicate "lvalues", and the use of "this" pointer to allow cascaded calls (e.g., a = b = c ).


7- I've enclosed links to download the COMPLETE version of this example. Below you'll find two links, one for the Array.h file and the other for the Array.cpp file. It is really a rich example to learn about operator overloading. Don't worry about copyrights, this example is completely FREE, says the author!





class Array


{


public:


Array ( int = 10 ); //default constructor


Array ( const Array %26amp; ); //copy constructor


const Array %26amp;operator= ( const Array %26amp; ); //overloaded (=)


private:


int size;


int *ptr;


}


--------------------------------------...


// overloaded assignment operator;


// const return avoids: ( a1 = a2 ) = a3


const Array %26amp;Array::operator=( const Array %26amp;right )


{


if ( %26amp;right != this ) // avoid self-assignment


{


// for Arrays of different sizes, deallocate original


// left-side array, then allocate new left-side array


if ( size != right.size )


{


delete [] ptr; // release space


size = right.size; // resize this object


ptr = new int[ size ]; // create space for array copy


} // end inner if





for ( int i = 0; i %26lt; size; i++ )


ptr[ i ] = right.ptr[ i ]; // copy array into object


} // end outer if





return *this; // enables x = y = z, for example


} // end function operator=


--------------------------------------...





Hope that helped!
Reply:try this tutorial: http://publib.boulder.ibm.com/infocenter...
Reply:class someClass


{


public:


...


someClass %26amp; operator=(const someClass %26amp;s);


...


}

narcissus

No comments:

Post a Comment