CSC/ECE 517 Fall 2010/ch5 5a MR

From Expertiza_Wiki
Jump to navigation Jump to search

Overloading

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 of Method Overloading

Disadvantages of Method Overloading

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. This will help us to prevent using functional-style syntax for manipulation.

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 :

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/Sstream library.
  • Syntax becomes more intuitive.
  • Elegently 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 predence or associativity of operators.
  • Code after operating overloading maybe visiually 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.