A block of code which runs only when its called is a function. Parameters can be passed into functions. They can be used repeatedly in the code.
How to create a function?
There are predefined functions like (main). But you can create other functions on your own to perform certain actions.
Syntax:
void myFunction() {
// code to be executed
}
Calling a Function
Functions are saved for further use after declaring them. You can call the function any number of times in the code. The program control is transferred to the function when it is called.
Example:
// Create a function void myFunction() { cout << "I just got executed!"; } int main() { myFunction(); // call the function return 0; }
Output:
“I just got executed!”
Function Parameters
A function must declare variables that accept the values if it has to use arguments. These variables that are declared are called the formal parameters of the function. They are created upon entry into the function and destroyed upon exit.
The values that are passed in the function call are called actual parameters. When the function is called, actual parameters get assigned to the corresponding formal parameters in the function definition.
Arguments can be passed to a function in the following two ways:
Sr.No | Call Type & Description |
---|---|
1. | Call by Value: This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. |
2. | Call by Reference: This method copies the reference of an argument into the formal parameter. The reference inside the function is used to access the actual argument we use in the call. Hence, the changes made to the parameter affect the argument. |
Function Overloading
In object oriented programming, two or more functions can have the same name but different parameters. This is called function overloading. The function name is overloaded with different jobs and gives different outputs when called.
Example:
#include <iostream>
using namespace std;
void print(int i) {
cout << " This is the integer "<< i << endl;
}
void print(double f) {
cout << " This is the float value "<< f << endl;
}
void print(char const *c) {
cout << " This is the character* "<< c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
return0;
}
Output:
Here is int 10 Here is float 10.1 Here is char* ten
Function overloading can be considered as an example of polymorphism feature in C++.