Wednesday, January 30, 2019

Function overloading in c++ programming

in this post, you will learn about the function overloading in c++ programming and learn why we overload the function in the program.

function overloading in c++ programming, c++ programming
learn c++ programming

Function overloading: 

to create one or more function using one name but with the different parameter is called function overloading.

Example:
                int first(void); // here the name of the function is first but there is no parameter
                int first(int a); // function name first with one integer value
                int first(int a, int b); // function name first with two integer values a and b
                int first(int a, float b); // function name first with one integer and one float value

Explanation:
in the above example, there are four functions with the same name first. but in all of the functions, there are different type parameters. so this functionality is called function overloading.

Note: you can change the return type of the functions.

How to call the overloaded functions:

to call the overloaded functions we use the parameters of the functions.

Example:

int first(void);
to call the above function we just need to call the function like this:

first(); 

int first(int a);
to call the above function we just need to pass the one integer value to the function.

first(10);

int first(int a, float b);
to call the above function we just need to pass the one integer and one float value to the function.

first(10, 20.22);

Example program for function overloading:

#include <iostream>

int calc(int);
int calc(int, int);

int main()
{
    int a,b;

    std::cout<<"\n enter the value for a and b";
    std::cin>>a>>b;

    calc(a);
    calc(b);
    calc(a,b);

    return 0;
}

int calc(int x)
{

    std::cout<<"\n you enter the value:"<< x;
 }

int calc(int x, int y)
{
    int c;
    c=x+y;
    std::cout<<"\n addition fo a and b is:"<< c;
}

I think now you fully understood how to overload the function. 

"please share this post as much as you can and also comment me your queries and question in the section given below"

0 comments: