Function Overloading

In C++, unlike C, you may have several functions with the same name. These functions must differ from each other in the parameters they accept. The main idea behind the decision to support this behavior was to allow the programmer the ability to use one function name for a particular task, regardless of the data type it worked with.

The C++ compiler decides which function to be called at compile time by examing the parameters to the function. Function Overloading is one of the ways in which C++ supports polymorphism. Overloaded functions don't need the same return type, but return type plays no part in determining which function to call..

void Print( int I );
void Print( long l );
void Print( float f );
void Print( int i,)
	cout << "Type integer: " << i << "\n";
void Print( float f )
	cout << "Type float: " << f << "\n";
void Print( long l )
	cout << "Type long: " << l << "\n";
void main( void )
	Print( 10 );
	Print( 100L );   // The L specifies a long datatype
	Print( 90.5F );	 // The F specifies a float datatype

Default Function Arguments

Another function-related difference between C++ and C is that C++ allows you to specify a default value for one or more parameters to a function. This value definition looks similar to an auto-initializing. The following is an example of a prototype that has a default value:

void ClearScreen( int Color = 7, int Lines = 25 );

ClearScreen( 0x70 );	// Will use default of 25 lines
ClearScreen( );		//Will use defaults of 7, 25

The definition of default argument values must occur in one place only, either the function definition, or prototype, but not both (even if the defaults are the same). It is recommended that the definitions be placed in the prototype so that they are accessable to other modules (assuming the prototype is in a .H file).