C++ Overloading Operators

CoderSource.net
C++ Overloading Operators
Rating: 4

Date: 5/1/2004 12:00:00 AM

   C++ overloading is the mechanism by which the language standard operators are used for customized operations of the classes. For example if we are trying to write a string class, we would very simply ask for "+" operator to handle string concatenation, "-" for removing one part of string from another etc., 
   This will put the users at ease. They need not worry about the internal handling of string operations or memory allocations. Instead they can start writing cleaner code concentrating only on the application functionality. Code Reusability becomes easier. Though the overloaded operators are very cleaner to use, the internals could be a little dirty. That is what, is the only problem/drawback with c++ overloading.   
   The developer of a class with such overloaded operators has to go through a painful set of coding to ensure the users are comfortable ( though at the developer's cost). All the operators can be overloaded except ., ?:, sizeof, ::, .* . Now let us see an example of using the "+" operator. 


//C++ overloading sample 
class MyString 

  public:
      char member1[100];
      void operator +(MyString val) 
      { 
           strcat(member1, val.member1); 
      }
 };


   The other intricacies of initializing the class, destructors etc., are left out for the sake of simplicity and readability. 
   Similar to the above example of c++ overloading, we can overload all other operators (except some) to give them a meaningful usage for the classes. 
   Usually unary operators may not need a parameter (or may need one at the most) and binary operators may need at least one parameter to be passed inside. This is how most of the times the logic on overloading works( and may differ too sometimes). Also some people will use techniques of passing a parameter to differentiate between a pre fix and post fix operators. 
   The stream operators << and << need a different type of treatment. Though these kind of techniques make the life of the developer difficult, it is the user who is going to be benefited the most.

 

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Codersource.Net Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us