Pages

Friday, September 29, 2017

Easy tutorial for C / C ++ Function 3 (Overloading)

Easy tutorial for C / C ++ Function 3 (Overloading)

Overloading

- Let's summarize the function overloading (Overloading). If you define functions that are used for similar purposes in your program, sometimes you may have too many named functions. Overloading is a function that can solve this problem.

- In order to distinguish each function, you must create a signature that can be distinguished. One way to do this is to use a different number of parameters and different types of arguments when using functions of the same name.

- Let's take a look at the example in the previous chapter. In the previous example, we defined three functions EXf1, EXf2, and EXf3 with different names. Let's change it to one name.

Previous Example

void EXf1();
void EXf2(int);
int  EXf3(int, int);

- There are three different named functions. Let's replace them with a single name, 'EX_f'.

Example Code

#include <iostream>
using namespace std;

void EX_f();
void EX_f(int);
int    EX_f(int, int);

int main() {
     cout << endl;
     cout << "##############################" << endl;
     cout << "           overloading         " << endl;
     cout << "##############################" << endl;
     cout << endl;

     EX_f();

     int n1, n2, n3 ;
     cout << "Enter a natural number between 0 and 10. : ";
     cin  >> n1 ;
     EX_f(n1);

     n2 = 10 ;
     n3 = EX_f(n1, n2);
     cout << n1 <<" + "<< n2 <<" = "<< n3 << endl;

     return 0;
}

void EX_f(){
cout << " No return values and parameters. " << endl;
}

void EX_f(int a){
           if(a > 3){
             cout<< a << " > 3 is true. "<<endl;
           }else{
             cout<< a << " <= 3 is true. "<<endl;
           }
}

int EX_f(int a, int b){
     int c ;
          c = a + b ;
          return c ;
}

- The "Overloading" message is displayed to distinguish it from the previous example. The other contents are the same as the previous example and all the function names are changed to 'EX_f'.

results:

##############################
           overloading        
##############################

 No return values and parameters.
Enter a natural number between 0 and 10. : 1
1 <= 3 is true.
1 + 10 = 11

- When you execute it, the phrase "Overloading" is output first.

(1) As a result of function 'EX_f ()' with no arguments and no return value, the statement "No return values and parameters. is printed."

(2) You have also printed a statement to enter a natural number between 0 and 10 as a result of a function 'EX_f ()' with an integer argument and no return value. If you type 1 here and press Enter, you will see "1 <= 3 is true."

(3) You can see that "1 + 10 = 11" is printed as a result of function 'EX_f ()' which has two integer type arguments and the integer data type of return value.

No comments:

Post a Comment