C++ Programming:-
In this tutorial you will learn:-
Function Overloading in C++
Function overloading means two or more functions can have an equivalent name, but either the amount of arguments or the info sort of arguments has got to vary . within the first example, we create two functions of an equivalent name, one for adding two integers and another for adding two floats. within the second program, we make two functions with identical names but pass them a special number of arguments. Function overloading is additionally referred to as compile-time polymorphism.
We created two functions "add" for integer and float data types, you'll create any number of them of an equivalent name as needed . Just confirm a compiler are going to be ready to determine which one to call. In the program, you'll create add function for long, double, and other data types.
Function overloading C++ program
#include <iostream>
using namespace std;
/* Function arguments are of different data type */
int add(int, int);
float add(float, float);
int main()
{
int a, b, x;
float c, d, y;
cout << "Enter two integers\n";
cin >> a >> b;
x = add(a, b);
cout << "Sum of integers: " << x << endl;
cout << "Enter two floating point numbers\n";
cin >> c >> d;
y = add(c, d);
cout << "Sum of floats: " << y << endl;
return 0;
}
int add(int x, int y)
{
int sum;
sum = x + y;
return sum;
}
float add(float x, float y)
{
float sum;
sum = x + y;
return sum;
}
In the functions, the code is that the same but data types are different, C++ provides an answer to the present problem. We can create one function for various data types which can reduce the dimensions of code by employing a feature of C++ referred to as templates.
C++ program for function overloading
using namespace std;
/* Number of arguments are different */
void display(char []); // print the string passed as argument
void display(char [], char []);
int main()
{
char first[] = "C programming";
char second[] = "C++ programming";
display(first);
display(first, second);
return 0;
}
void display(char s[])
{
cout << s << endl;
}
void display(char s[], char t[])
{
cout << s << endl << t << endl;
}
Output of program:
C programming
C++ programming
A function return type has no role because it returns a value when called and at compile time compiler will not be able to decide which one to call.
0 comments:
Post a Comment
If you have any doubt, please let me know