Wednesday, November 15, 2023

Function Overloading

Function overloading means two or more functions can have the same name but either the number of arguments or the data type of arguments has to be different. Return type has no role because function will return a value when it is called and at compile time compiler will not be able to determine which function to call.

When you call an overloaded function, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.

There are two ways to overload the functions in C++:

1. Changing number of Arguments:

In this type of function overloading we define two or more functions with same names but different number of parameters of the same type.

2. By having different types of argument:

In this type of function overloading we define two or more functions with same names and same number of arguments but the type of arguments is different.

Matching Function calls with over loaded functions

When an overload function is called, one of the following cases occurs:

Case 1: A direct match is found, and there is no confusion in calling the appropriate overloaded function.

Case 2: If a match is not found, a linker error will generate. However, if a direct match is not found, then, the compiler will try to find a match through the type conversion or type casting.

Case 3: If an ambiguous match found, that is when the arguments match more than one  overloaded function, a compiler error will be generated.

For example:

#include<iostream.h>

void print(int n)

{

Cout<<”n= “<<n<<”\n”;

}

Void print(char c)

{

Cout<<”ch= “<<ch<<”\n”;

}

Void print(float f);

{

Cout<<”f= “<<f<<”\n”;

}

Void main()

{

Print(8);

Print(‘D’);

Print(25.4);

}

When you execute this code, you will get a compile time error as there are two function declarations are valid for print(8); The function call can invoke either int or float version because all standard type conversions are treated equal. Therefore, 8 can be treated as an int as well as a float.


0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top