// Example 1
int Double( int value )
{
return 2 * value;
}
That would return an int, but what if you wanted to double a float? MSVC++6 would give you a warning saying that converting this could result in data loss.// Example 2
float DoubleForFloats( float value )
{
return value * 2.0;
}
but then you'd have to write and call a different function. Here's how it's done with Function Overloading :
// Example 3
int Double( int value ) { return value * 2; };
float Double( float value ) { return value * 2.0; };
As you can see both functions have the same name, but their type is different and the value you pass is off a different type as well. Yet your compiler doesn't give you an error of duplicate declaration. (at least mine didn't :D)// Example 4 :]
#include "stdio.h"
int PrintValue( int value, int repeat );
int PrintValue( float value, int repeat );
int main()
{
int the_int = 10;
float the_float = 12;
PrintValue( the_int, 3 );
PrintValue( the_float, 3 );
return 0;
}
int PrintValue( int value, int repeat )
{
for ( int a = 1; a < repeat + 1; a++ )
{
printf("The int value is %d, and this has been
repeated %d times...
", value, a );
}
return 0;
}
int PrintValue( float value, int repeat )
{
for ( int a = 1; a < repeat + 1; a++ )
{
printf("The float value is %f, and this has been
repeated %d times...
", value, a );
}
return 0;
}
You could just as well use this for Half-Life, to change health for monsters. You could cast this, but you wouldn't be able to call monster specific stuff.// Example 5
int SetHealth( CBaseEntity *pEntity, int health );
int SetHealth( CBasePlayer *pPlayer, int health );
int SetHealth( CBaseMonster *pMonster, int health );
.. Call this with SetHealth( pEntity, 100 ); ..// Example for the CBaseEntity
int SetHealth( CBaseEntity *pEntity, int health );
{
if ( pEntity && pEntity->IsAlive() )
pEntity->pev->health = health;
return 0;
}
But even this way you'd already save a line, as all you have to do then is SetHealth( pEntity, 100 ); and it would check for you if the entity you send is both existing AND alive, saving you the if line and the risk of crashes if you don't do that.You must log in to post a comment. You can login or register a new account.