Page 65 - DCAP404 _Object Oriented Programming
P. 65

Object-oriented Programming




                    Notes          Now suppose we want the function to take float type argument then the function definition
                                   must be changed as:

                                          float  sumfloat(float  a,  float  b)
                                          {
                                                 return  (a  +  b);
                                          }
                                   As a matter of fact the function sum may take so many names as shown below.
                                          int  sumint(int  a,  int  b)
                                          {
                                                 return  (a  +  b);

                                          }
                                          short  sumshort(short  a,  short  b)
                                          {
                                                 return  (a  +  b);
                                          }
                                          long  sumlong(long  a,  long  b)
                                          {

                                                 return  (a  +  b);
                                          }
                                          float  sumdouble(double  a,  double  b)
                                          {
                                                 return  (a  +  b);
                                          }
                                   This can be very tiring and extremely difficult to remember all the names. Function overloading
                                   is a mechanism that allows a single function name to be used for different functions. The compiler
                                   does the rest of the job. It matches the argument numbers and types to determine which functions
                                   is being called. Thus we may rewrite the above listed functions using function overloading as:
                                          int  sum(int  a,  int  b)
                                          {
                                                 return  (a  +  b);
                                          }

                                          float  sum(float  a,  float  b)
                                          {
                                                 return  (a  +  b);
                                          }
                                          short  sum(short  a,  short  b)
                                          {
                                                 return  (a  +  b);




          58                                LOVELY PROFESSIONAL UNIVERSITY
   60   61   62   63   64   65   66   67   68   69   70