(This question has been asked in GU Uni Dec 2018 for 7 Mark)

In C++, two functions can have the same name if the number and/or type of arguments passed is different.

These functions having the same name but different arguments are known as overloaded functions. For example:

Below program has two different functions namely myFun. The first function takes only one argument and the Second function takes two arguments. Note that both functions has the same name but they have a different number of arguments.

Whenever we are calling function myFun from main function compiler will decide which function to be called based on the number and type of arugment.

If we passed only one argument first function with single argument will be called. If we pass two argument second function will be called. This is clearly visible from the output of the function with cout statement telling us which function is called.

Depending on the number and type of arguments passed, the corresponding myFun() function is called.

#include <iostream>
using namespace std; 

int myFun(int x )
{
    cout<<"Function with one argument  called"<<endl; 
    return x; 
}
int myFun(int x, int y)
{
    cout<<"Function with two arguments  called"<<endl; 
    return x+y; 
}

int main()
{
    int a=5; 
    int b=3; 
    int c; 
    int d; 
    c=myFun(a); 
    cout<<"c: "<<c<<endl; 
    d=myFun(a,b); 
    cout<<"d: "<<d<<endl; 
    return 0; 
}

OUTPUT:

Function with one argument  called
c: 5
Function with two arguments  called
d: 8

https://github.com/amitntrivedi/ObjectOrientedConceptsandProgramming/blob/master/Classes%20And%20Objects/FunctionOverloading.cpp

Write a short note on Function Overloading in C++

Leave a Reply

Your email address will not be published. Required fields are marked *