CSC/ECE 517 Fall 2010/ch5 5a MR: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 59: Line 59:
=='''Disadvantages'''==
=='''Disadvantages'''==
* If not used properly ,such as using functions with the same name for different purposes, method overloading cause considerable confusion.
* If not used properly ,such as using functions with the same name for different purposes, method overloading cause considerable confusion.
* The mixing of overloads and default parameter values can also lead to unexpected results. In the example below, both the methods can be called with a single parameter which would lead to confusion.This applies equally to constructors that mix specific overloads and default parameters.<br />
* The mixing of overloads and default parameter values can also lead to unexpected results. In the example below, both the methods can be called with a single parameter which would lead to confusion.This applies equally to constructors that mix specific overloads and default parameters.
 
<pre>
     void example(int x);<br />
     void example(int x);
     void example(int x, int y = 1);<br />
     void example(int x, int y = 1);
 
</pre>
*Another problem occurs when mixing integer and pointer types:<br />
*Another problem occurs when mixing integer and pointer types:
 
<pre>
     void example(int x);<br />
     void example(int x);
     void example(int * ptr);<br />
     void example(int * ptr);
 
</pre>
In the above example, a call to ''example(NULL'') could be taken as ''example'' being passed a zero valued integer or a null pointer value, leading either to the overload of ''example'' taking an int being called or to an ambiguity giving a compiler error, depending on compiler's interpretation of C++. In the case of a constructor it may mean that the object is created in the wrong manner.
In the above example, a call to ''example(NULL'') could be taken as ''example'' being passed a zero valued integer or a null pointer value, leading either to the overload of ''example'' taking an int being called or to an ambiguity giving a compiler error, depending on compiler's interpretation of C++. In the case of a constructor it may mean that the object is created in the wrong manner.



Revision as of 22:10, 3 November 2010

Overloading -- good or bad ?


Introduction

Overloading is one of the best ways to implement polymorphism. Overloading as such refers to a technique in which more than one method (function) having the same name can be present in a program. The compiler will resolve which method to be invoked depending upon the signature of the method. This is called Method Overloading. Another type of overloading is the Operator Overloading which refers to giving additional meaning to normal C++ operators when they are applied to Abstract Data Types (ADT). An operator can be overloaded by defining a function for it.


Method Overloading

Many programming languages like C++, Java, C# provide method overloading which allows a programmer to write multiple methods with the same name but that which perform a variety of different tasks. This makes an operation more generic in that, the same operation can now be called upon in different ways depending on the circumstances. A method is overloaded when we can find multiple methods in a single class with the same name but with different number and/or type of parameters that is used to define the methods. The return type of the overloaded methods have to be the same else the compiler would not be able to identify the overloaded methods.

Example:

int area( int a );
int area( double a ); 
int area( int a, int b );

double area( int a ); // not allowed

In the above example, the first two methods differe by their parameter types and the third one differs by the number of parameters. The fourth example is considered to be equivalent to the first, so is not an overloaded method.

Constructor Overloading

Overloading constructors, like overloading other method names, is just the practice of defining more than one constructor for a class, each taking a different set of parameters. In this sense, a copy constructor is nothing but an overloaded method of the default constructor.

Example:

class Example
{
public:
        Example();                   // Default constructor
        Example( Example const &obj);  // Copy constructor
        Example(int a, float b); // Another overloaded constructor
// ...
};
Example obj1;              // default constructed
Example obj2( obj1 );  // copy constructed
Example obj3(3,4.5);

Advantages

  1. When ever some new features are added in a new version, method over loading can be used to add a new method with support for new version without disturbing the existing methods with features of previous version.
  2. Apart from the obvious advantage that it makes a method more versatile, method overloading also saves memory.
  3. One of the main advantages of method overloading is that it increases code readability and tidies the code. Let us consider the example of String.valueOf method[4] in Java. Given any type of variables, we can get a String representation of it by using the String.valueOf method. Some of the overloaded versions of this method are defined as:
   static String valueOf(boolean b) 
   static String valueOf(char c) 
   static String valueOf(long l) 
   static String valueOf(Object obj) 

If overloading was not allowed we'd have methods that look like this:

static String valueOfBoolean(boolean b) 
static String valueOfChar(char c) 
static String valueOfLong(long l) 
static String valueOfObject(Object obj) 

which is very harder to read than the overloaded solution.

Disadvantages

  • If not used properly ,such as using functions with the same name for different purposes, method overloading cause considerable confusion.
  • The mixing of overloads and default parameter values can also lead to unexpected results. In the example below, both the methods can be called with a single parameter which would lead to confusion.This applies equally to constructors that mix specific overloads and default parameters.
    void example(int x);
    void example(int x, int y = 1);
  • Another problem occurs when mixing integer and pointer types:
    void example(int x);
    void example(int * ptr);

In the above example, a call to example(NULL) could be taken as example being passed a zero valued integer or a null pointer value, leading either to the overload of example taking an int being called or to an ambiguity giving a compiler error, depending on compiler's interpretation of C++. In the case of a constructor it may mean that the object is created in the wrong manner.

Operator Overloading

Operators can be applied on primitive types. When it is possible to define user-defined classes that can interact with these operators, it is called Operator Overloading. In simple words, it means that a single operator can handle multiple argument types.

To define an overloaded operator, a function operator # is defined. The # represents the operator that is to be overloaded.

Example: operator +, operator >>

The overloading is actually done in C++ by replacing instance of every operator with the a call to the operator function.

Example:

         int a,b,c;
         a = b*c;

It is equivalent to -

        int a,b,c;
        a.operator = (operator+(b,c));

Some operators cannot be overloaded because of their requirement at compile-time.

Examples of such operators are:

All the other operators can be overloaded.

In a broad sense, operators are classified into -

  • Arithmetic Operators
  • Relational Operators
  • I/O Operators

The operator overloading for each type follows.

Arithmetic Operators

It includes +=,-=,*=,/=,%= and their corresponding binaries are +,-,*,/,% respectively. Generally arithmetic assignment operators can be implemented as member functions. These can then be used to implement the binary operators that are normally independent, non-member functions. The problem in making it a member function is that it requires an object to which it can be applied [1].

Overloading of Arithmetic Assignment Operator

Example: [1]

const BigInt& BigInt::operator += (const BigInt & rhs)
// post condition : rhs has to be added to *this
// *this has to be returned

BigInt a = Factorial(25);
BigInt b = Factorial(30);

Then the overloaded function is called as -

         a+=b;
         BigInt c = (b+=b); 

The arithmetic assignment operators should return a value. The return type should be a reference and also a constant.

More information on overloading Arithmetic Assignment operators can be obtained from [1].

Overloading of Binary Operator

Example: [2]

Let us define a class Matrix.

class Matrix 
   {     public :
          /* other member functions */
          MATRIX &operator *= (double scalar);

         private :
          static const int MATRIX_SIZE =3;
          double entries[MATRIX-SIZE][MATRIX_SIZE];
   };
            
const Matrix operator *(double scalar) const
     {    MyMatrix result = *this;
          result*=scalar;
          return result;
     }

The *= operator will scale all the elements in the matrix by a double factor. The function can now be called as

                     myMatrix = myMatrix * 2.3471;

More information on overloading of binary operators can be obtained from [2].

Relational Operators

Some of the relation operators are <,>,==,!,!=,&& which have a return type of bool. The relational operator overloading functions are defined to give a global access so that they can be used without any worry about the order in which the arguments passed.

Overloading of Relational Operators

Example : [2]

bool operator==(const Date & lhs, const Date & rhs);
bool operator<(const Date &lhs, const Date & rhs);

bool operator==(const Date & lhs, const Date & rhs)
{    
   return lhs.equal(rhs);
}

bool operator<(const Date & lhs, const Date & rhs)
{
   return lhs.less(rhs);
}

This shows the declaration and defintion for overloading == and < operator. The function for operator == will return true if lhs is equal to rhs and false otherwise. Similarly, the function for operator < will return true if lhs is less than rhs and false otherwise.

More information on overloading of Relational Operators can be obtained from [1] and [3].

I/O Operators

Some examples of I/O Operators are << and >> i.e the ostream and istream operators. Both the operators are left-associated, meaning they evaluate the expression from left to right like,

(((cout<<1)<<2)<<endl); [2]

Overloading of I/O Operators

Example : [2]

ostream&operator<<(ostream & out, const BigInt & big)
      {   out<<big.tostring();
          return out;
      }
BigInt b = Factorial(25);
string s = "factorial ";

cout<<s<<b; // function call

The function overloads the ostream operator << to return the integer value converted to string.

More information about overloading of I/O Operators can be obtained from [1] and [2].

Other Overloadable Operators

Overloading of Bracket Operator

The bracket operator when it is overloaded will return a reference to the data which is stored in the function.

Example : [2]

for(int i =0;i< myVector.size();i++)
myVector[i]=120;

This is equivalent to

myVector.operator[](i) = 120;

The overloading function is defined as -

char& operator [] (int postion) { }

More information on Overloading of Bracket Operator is obtained usin [2].

Overloading new and delete Operators

This facilitates changing memory allocation at run time i.e how much memory is allocated at run time can be changed. The syntax still remains to be new MyClass and it cannot be overloaded.

More information about other overloadable operators can be obtained from [2].

Advantages

  • Enables custom classes to act like primitive types - If we have a class vector which resembles standard array notation, it will be possible to array to access the individual elements.
  • Enables our code to interact correctly with library and template code - Overloading << to be compatible standard I/O Stream library.
  • Helps us to prevent using functional-style syntax for manipulation.
  • Syntax becomes more intuitive.
  • Elegantly performs complex operations behind the scenes. [3]

Disadvantages

  • All operator overloaded functions must contain one user-defined type so that the basic meaning of operators is not redefined.
  • Some operators cannot be overloaded.
  • Cannot define additional operators.
  • Cannot change precedence or associativity of operators.
  • Code after operating overloading maybe visually correct but might contain serious code errors.
  • Operators defined by programmers may not be semantically meaningful.
  • Wrong return type may be provided. [3]

Conclusion

References

External Links

[1] Overloading Arithmetic and Relational operators

[2] Overloading Relational and I/O Operators

[3] Overloading Relational Operators, Advantages and Disadvantages.

[4] Advantages of Method Overloading in Java