Header Ads Widget

What is function overloading in C++ and how it works ?

 It is possible in C++ to use the same function name for a number of times for different intentions. Defining multiple functions with same name is known as function overloading or function polymorphism. The overloaded function must be different in its argument list  and with different data types. The function would perform different operations depending on the argument list in the function call. The correct function to be invoked is determined by checking the number and type of arguments but not on the function type.

If two functions have the similar number of arguments and their  data types the function can not be overloaded. The return type may be similar or void but number of arguments or data types of arguments must be different.

The compiler attempts to find an accurate function definition that matches in types and number of arguments and invokes that function. The arguments passed are checked with all declared functions. If matching function is found then that function gets executed. If an exact match is not found the compiler makes the implicit conversion of actual argument. 

#include <iostream>

using namespace std;

int volume (int);

double volume (doubleint);

int main()

{

    cout << "Volume of Cube ="<< volume(20) <<"\n";

    cout << "Volume of Cylinder ="<< volume(4.5, 5) <<"\n";

    return 0;

}

int volume (int x)

{

    return (x*x*x);

}

double volume (double r, int h)

{

    return (3.14*r*r*h);

}


Post a Comment

0 Comments