1.5.2 Defining and Calling Functions

In this example, you will explore the basics of defining and calling a function. Remember, one of the reasons we use functions is to produce reusable code. Once a function is defined, it can be called multiple times.

Defining Functions

The basic function definition syntax in C++ is similar to other languages:

returnType functionName(parameter list){
    function statements
}

The one noticeable difference from Java is that there is no public/private access level at the beginning. By default, functions are public. In this course, we will always use public functions.

Let’s take a look at each of these components:

returnType: Each function needs either a variable type or void return type.

functionName: The second value should be the function name. By convention, these typically start with a lowercase value.

parameter list: The parameters should specify both the variable type and the variable name. Each parameter is separated by a comma. Parameters are optional.

function statements: The body of the function is put between the curly braces.

Examples:

int addFive (int number){
    number += 5;
    return number;
}
void printSum (int num1, int num2){
    cout << num1 + num2 << endl;
}

Calling a Function

You can call a function by using its name and passing any applicable parameters. If the function has a return value, you can process that return value as needed.

Function Definition:

int addFive (int number){
    number += 5;
    return number;
}

Calling the Function:

int main(){
    int a = addFive(8);
    return 0;
}

Function Overload

As you see in other languages, C++ allows for function overloads. Two functions can share the same name as long as they have different parameters (as defined by the parameter type and order).

Using function overload helps to keep function names the same even if different parameters are needed. For example, if you think back to the substring function, there was a version that took a starting point and a version that took a starting point and length. Using function overload, you can name these functions the same and the compiler will figure out which function to use based on the parameter list.

Good Examples

Bad Examples

int addNum(int a, int b) {…} int addNum(int a, int b, int c) {...}

int addNum(int a, int b) {…} int addNum(int x, int y) {...}

string remove(string s, int start) {...} string remove(string s, int start, int end) {...}

string insert(string s, int start, int end) {...} string insert(string s, int end, int start) {...}

In the table above, the first set of bad examples just change the variable name. Just changing the name does not create a different function signature since the variable types are the same.

The second bad example has a similar issue. In this example, the variable order is switched, but since the variables have the same types, they do not override.

Try This Example

Last updated