I l@ve RuBoard Previous Section Next Section

2.6 Providing Overloaded Functions

Rather than have each function generate its own diagnostic messages, let's provide a general display_message() function. It might be used as follows:



bool is_size_ok( int size ) 


{ 


     const int max_size = 1024; 


     const string msg( "Requested size is not supported" ); 





     if ( size <= 0 || size > max_size ){ 


          display_message( msg, size ); 


          return false; 


     } 


     return true; 


} 

Similarly, our program in Chapter 1 might use it to display its greeting to the user



const string 


      greeting( "Hello. Welcome to Guess the Numeric Sequence" ); 





display_message( greeting ); 

and to display the two elements of the sequence:



const string seq( "The two elements of the sequence are " ); 


display_message( seq, elem1, elem2 ); 

In another instance, we might want to use display_message() simply to output a newline or tab character:



display_message( '\n' ); display_message( '\t' ); 

Can we really pass parameters to display_message() that differ both in type and number? Yes. How? Through function overloading.

Two or more functions can be given the same name if the parameter list of each function is unique either by the type or the number of parameters. For example, the following declarations represent the four overloaded instances of display_message() invoked earlier:



void display_message( char ch ); 


void display_message( const string& ); 


void display_message( const string&, int ); 


void display_message( const string&, int, int ); 

How does the compiler know which instance of the four overloaded functions to invoke? It compares the actual arguments supplied to the function invocation against the parameters of each overloaded instance, choosing the best match. This is why the parameter list of each overloaded function must be unique.

The return type of a function by itself does not distinguish two instances of a function that have the same name. The following, for example, is illegal. It results in a compile-time error:



// error: parameter list not return type must be unique 


ostream& display_message( char ch ); 


bool display_message( char ch ); 

Why isn't the return type itself sufficient to overload a function? It is because the return type cannot guarantee a sufficient context with which to distinguish instances. For example, in the following call there is really no way for the compiler to determine which instance the user wished to have invoked:



display_message( '\t' ); // which one? 

Overloading a set of functions that have unique implementations but perform a similar task simplifies the use of these functions for our users. Without overloading, we would have to provide each function with a unique name.

    I l@ve RuBoard Previous Section Next Section