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

From Expertiza_Wiki
Jump to navigation Jump to search
Line 6: Line 6:
Example:
Example:
<pre>
<pre>
int func( int a );
int area( int a );
int func( double a );  
int area( double a );  
int func( int a, int b );
int area( int a, int b );


double func( int a ); // not allowed
double area( int a ); // not allowed
</pre>
</pre>
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.
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.

Revision as of 15:52, 3 November 2010

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

Operator Overloading

The ability to define how user defined classes interact with operators applicable to primitive types 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:

  • :: => Scope Resolution
  • . => Member Selection
  • ?: => Ternary Conditional
  • sizeof => Size of Object

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. It is easy to implement arithmetic assignment operators as member functions and using these to implement the binary operators. Usually binary operators are implemented as 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 to avoid copy and it must be 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 generally globally defined so that they can be used without any worry about the order 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 returns a reference to the data stored in the class.

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== [3]

  • 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.

==Disadvantages== [3]

  • 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.

Conclusion

References

External Links

[1] Overloading Arithmetic and Relational operators

[2] Overloading Relational and I/O Operators

[3] Overloading Relational Operators, Advantages and Disadvantages.