WEB DEVELOPER SITE
PYTHONPHPJAVA
 

C++ Overloading


Function overloading allows to create multiple functions with the same name, so long as they have different parameters.

you might need a printNumber() function that prints the value of its parameter.
void printNumber(int a) { 
  cout << a;
}



This is effective with integer arguments only. Overloading it will make it available for other types, such as floats.

void printNumber(float a) { 
  cout << a;
}

Function Overloading

#include 
using namespace std;

void printNumber(int x) {
    cout << "Prints an integer: " << x << endl;
}
void printNumber(float x) {
    cout << "Prints a float: " << x << endl;
}

int main() {
    int a = 12;
    float b = 14.541;
    printNumber(a);
    printNumber(b);
}
/* Output:  
Prints an integer: 12
Prints a float: 14.541
*/
Note
As you can see, the function call is based on the argument provided. An integer argument will call the function implementation that takes an integer parameter. A float argument will call the implementation taking a float parameter.

Recursion

A recursive function in C++ is a function that calls itself.
To demonstrate recursion, let's create a program to calculate a number's factorial. In mathematics, the term factorial refers to the product of all positive integers that are less than or equal to a specific non-negative integer (n). The factorial of n is denoted as n!
Example
4! = 4 * 3 * 2 * 1 = 24
define function
int factorial(int n) {
  if (n==1) {
    return 1;
  }
  else {
    return n * factorial(n-1);
  }
}

Arrays and Functions

An array can also be passed to a function as an argument.
void printArray(int arr[], int size) {
  for(int x=0; x

Arrays and Functions

we can call array and function
#include 
using namespace std;

void printArray(int arr[], int size) {
    for(int x=0; x
using namespace std;

void printArray(int arr[], int size) {
    for(int x=0; x

The printArray function takes an array as its parameter (int arr[]), and iterates over the array using a for loop.

Function Arguments

There are two ways to pass arguments to a function as the function is being called.
  • By value: This method copies the argument's actual value into the function's formal parameter. Here, we can make changes to the parameter within the function without having any effect on the argument.
  • By reference: This method copies the argument's reference into the formal parameter. Within the function, the reference is used to access the actual argument used in the call.

Passing by Value

By default, arguments in C++ are passed by value.

void myFunc(int x) {
    x =200;
}

int main() {
    int var = 10;
    myFunc(var);
    cout << var;
}