Function (computer programming): Difference between revisions

Content deleted Content added
top: Removed the parenthetical in "'''subroutine''' (when it doesn't return a value)". This usage distinction exists but isn't adhered to in general.
Overloading: Added comments to the code block to make it understandable to more people
Line 360:
In [[object-oriented programming]], when a series of functions with the same name can accept different parameter profiles or parameters of different types, each of the functions is said to be [[method overloading|overloaded]].
 
Here is an example of function overloading in [[C++]], demonstrating the implementation of two functions with the same name (Area) but different parameters:
<syntaxhighlight lang="cpp">
#include <iostream>
 
double Area(double h, double w) { return h * w; }
/* The first Area function is for finding the area of a rectangle, so it accepts two numbers as parameters, to represent the height and width. */
 
double Area(double r) { return r * r * 3.14; }
/* The second Area function is for finding the area of a circle, so it only accepts one number as a parameter, to represent the radius. */
 
int main() {
double rectangle_area = Area(3, 4); //This calls the first Area function, because two parameters are provided.
double circle_area = Area(5); //This calls the second Area function, because only one parameter is provided.
 
std::cout << "Area of a rectangle is " << rectangle_area << std::endl;
Line 376 ⟶ 378:
}
</syntaxhighlight>
In this code, there are two functions of the same name but they have different parameters.
 
As another example, a function might construct an [[object (computer science)|object]] that will accept directions, and trace its path to these points on screen. There are a plethora of parameters that could be passed in to the constructor (colour of the trace, starting x and y co-ordinates, trace speed). If the programmer wanted the constructor to be able to accept only the color parameter, then he could call another constructor that accepts only color, which in turn calls the constructor with all the parameters passing in a set of ''default values'' for all the other parameters (X and Y would generally be centered on screen or placed at the origin, and the speed would be set to another value of the coder's choosing).