Articles

What is function overloading in c++ with example?

What is function overloading in c++ with example?


In this c++ interview questions, we will learn:

  • what is function overloading in c++?
  • example of function overloading in c++

What is function overloading in c++?

Function overloading in c++ is an important feature that helps implement polymorphism (to be more precise compile time polymorphism). Here we will learn about what is function overloading in c++ with example.

 

Function overloading technically refers to multiple definitions for the same function name in the same scope.

In more simple words, we can say function overloading allows us to define multiple functions with same name but different parameters. 

 

Example of function overloading in c++

For example, 

int area(int r)
float area(float l, float b, float h)
double area(double l, double b)

Here we have overloaded method named 'area' with different parameter list. We can call anyone depending on our requirement for specific purpose. Like first one can be used to calculate area of circle by passing radius, second one can be used to calculate area of traingle passing length, base and height while last one can be used to calculate area of rectangle with length and breadth as input parameter.

 

Basic thing that we want you to understand is, you can overload function in c++ in similar way by changing number of parameter or its data type and keeping the method name same.

 

The definition of the function must differ from each other by different parameters or arguments list.

 

Example:

#include<iostream>
using namespace std;
float add(float i,float j)
{
    return (i+j);
}
int add(int i,int j)
{
    return (i+j);
}

int main()
{
    int a=10;
    int b=12;
    float x=2.25;
    float y=3.69;
    cout<<"Float addition"<<" "<<add(x,y)<<endl;
    cout<<"Int addition"<<" "<<add(a,b)<<endl;
    return 0;
}

 Output:

Float addition 5.94

Int addition 22

 

In the above code add() called for two times with different arguments. On basis of number and argument passed corresponding add() is called.

 

Note: Function can't be overloaded not only depends upon return type, one parameter must of a different type.


cpp interview questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Subhajit Guha Thakurta
Page Views :    Published Date : Apr 02,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!