Cpp - Use Overloaded Function

Introduction

C++ can overload functions, that is, different functions can have the same name.

int    max( int x, int y); 
double max( double x, double y); 

In the example two different function share the same name, max.

The function max() was overloaded for int and double types.

The compiler uses a function's signature to differentiate between overloaded functions.

Function Signatures

A function signature includes the number and type of parameters.

When a function is called, the compiler compares the arguments to the signature of the overloaded functions and calls the appropriate function.

double maxvalue, value = 7.9; 
maxvalue = max( 1.0, value); 

In this case the double version of the function max() is called.

When overloaded functions are called, implicit type conversion takes place.

This can lead to ambiguities, which in turn cause a compiler error to be issued.

maxvalue = max( 1, value);   // Error! 

The signature does not contain the function type, since you cannot deduce the type by calling a function.

The following code shows how to use overloaded functions to generate random numbers.

Demo

#include <iostream> 
#include <iomanip> 
#include <cstdlib>     // For rand(), srand() 
#include <ctime>       // For time() 
using namespace std; 

bool setrand = false; 
inline void init_random()  // Initializes the random 
{                          // number generator with the 
                                // present time. 
   if( !setrand ) 
    {  srand((unsigned int)time(NULL)); 
       setrand = true; 
    } // ww w.  j  av a2  s. c  om
} 
inline double myRandom()           // Returns random number x 
{                            // with  0.0 <= x <= 1.0 
   init_random(); 
   return  (double)rand() / (double)RAND_MAX; 
} 
inline int myRandom(int start, int end)  // Returns the 
{                               // random number n with 
   init_random();               // start <= n <= end 
   return (rand() % (end+1 - start) + start); 
} 

int main() 
{ 
   int i; 
   cout << "5 random numbers between 0.0 and 1.0 :" 
         << endl; 
   for( i = 0; i < 5; ++i) 
       cout << setw(10) << myRandom(); 
   cout << endl; 
   cout << "\nAnd now 5 integer random numbers " 
             "between -100 and +100 :" << endl; 
   for( i = 0; i < 5; ++i) 
       cout << setw(10) << myRandom(-100, +100); 
   cout << endl; 
   return 0; 
}

Result

Related Topic