function overloading

  1. Allows more than one function to share the same name.
  2. Overloaded function must have a unique signature in either the number or types of their arguments.
  3. Relieves the user of a library from having to remember function names that perform identical actions.

    The return type of a function is ignored while determining overloaded instances

Signatures are different in either the types or number of their arguments.
These instances are considered to be overloaded.

int func(int,int);
int func(int,int,int);
double func(double,double);


The following attempt to overload Func_t() is erroneous.

void Func_1(int);
void Func_!(int&);
void Func_1(const int);

Argument matching rules.

1.Exact match and trivial conversions.
2.Match using promotions.
3.Match using standard conversions.
4.Match using user-defined conversions.

Rule 1. Exact match and trivial conversions
exact match scenario

void Disp(char);
void Disp(int);
void Disp(int&,char&);
void Disp(const char,const int);

int v = 13;
char c = ‘v’;
Disp(v); //will invoke Disp(int)
Disp( c ); //will invoke Disp(char)


Trivial conversions.
t to t&
t& to t
t[ ] to t*
t to const t
F(arg-list) to (*F)(arg-list)

void Disp(char);
void Disp(int);
void Disp(int&,char&);
void Disp(const char,const int);
int v = 13;
char c = ‘v’;
Disp(c,v); //will invoke Disp(const char , const int)
Disp(v,c); //will invoke Disp(int &, char&)

Rule 2. Match using promotions


A char, short int can be promoted to an int.
A float can be promoted to a double.
void Disp(int);
void Disp(double);
char c;
short int s;
float f;
Disp( c) ; // will invoke Disp(int)
Disp( s); // will invoke Disp(int)
Disp( f); // will invoke Disp( double)


Rule 3. Using standard conversion
Uses standard type conversion between one primitive type to another primitive type.
Possible loss of data due to conversion.
void Disp(double);
void Disp( void *);
int v;
char *s;
Disp(v); //Disp(double);
Disp(s); //Disp(void *);

No comments: