on Leave a Comment

C++ Function Overloading Concept

Overloading refers to use of same thing but for different purposes. C++ allows function overloading. Function overloading refers to use of two or more functions having same name but containing different arguments. With the concept of function overloading, we can use numbers of functions with one name, but having different arguments list. During function calling correct function is determined by number and type of arguments but not on the function type.

For example, a function sum can be overloaded in different ways:

int sum(int a,int b);
int sum(int a,int b,int c);
float sum(float x,float y);

Example of Function Overloading in C++

/*C++ program to calculate area of circle and rectangle using function overloading*/

#include<iostream>
using namespace std;
void area(float r);
void area(float a,float b);
int main()
{
    float a,b,r;
    cout<<endl<<"Enter the radius of circle : ";
    cin>>r;
    area(r);
    cout<<endl<<"Enter the length and breadth of rectangle : ";
    cin>>a>>b;
    area(a,b);
    return 0;
}
void area(float r)                      //Area of Circle
{
    cout<<"Area of circle is "<<3.14*r*r;
}
void area(float a,float b)           //Area of rectangle
{
    cout<<"Area of rectangle is "<<a*b;
}

OUTPUT:

Enter the radius of circle : 6
Area of circle is 113.04
Enter the length and breadth of rectangle : 3 5
Area of rectangle is 15

This program having two area function, first area function having one arguments, second area function having two arguments.  

How function overloading is resolved by compiler?

The compiler first find exact match in which the types of actual arguments are same and use that function.

If no exact match is found, C++ compiler uses integral promotion.
-char, unsigned char and short to int.
-float to double

If no exact match is found, C++ compiler tries match through standard conversion.

   

0 comments:

Post a Comment