Methods
Lesson 14Author : Afrixi
Last Updated : November, 2022
In C++, methods are also known as functions. A function is a block of code that performs a specific task and can be called from different parts of a program. Here’s an example of how to create and use a function in C++:
#include <iostream>
// Function declaration
int addNumbers(int a, int b);
int main() {
int x = 5;
int y = 10;
int result = addNumbers(x, y);
std::cout << "The sum of " << x << " and " << y << " is " << result << std::endl;
return 0;
}
// Function definition
int addNumbers(int a, int b) {
return a + b;
}
In this code, a function called addNumbers
is declared and defined. The function takes two integer parameters a
and b
, and returns the sum of the two parameters.
In the main function, we declare two integer variables x
and y
, and initialize them with the values 5 and 10 respectively. We then call the addNumbers function and pass in x
and y
as arguments. The return value of the function is assigned to a variable called result
.
Finally, we print a message to the console that displays the values of x
, y
, and result using std::cout
.
Functions can also be used to modify the values of variables. Here’s an example of how to create a function that modifies the value of a variable:
#include <iostream>
// Function declaration
void square(int& x);
int main() {
int y = 5;
square(y);
std::cout << "The square of 5 is " << y << std::endl;
return 0;
}
// Function definition
void square(int& x) {
x = x * x;
}
In this code, a function called square
is declared and defined. The function takes an integer reference parameter x
, which means that any changes made to x
inside the function will affect the original variable passed in as an argument.
In the main
function, we declare an integer variable y
and initialize it with the value 5. We then call the square
function and pass in y
as an argument. The square
function squares the value of y
, which modifies the original variable. Finally, we print a message to the console that displays the value of y
using std::cout.