Recall Functions in C++
Lesson Introduction
Welcome to the lesson on recalling functions in C++. Functions are fundamental building blocks that allow for code modularity, reusability, and better organization. Understanding functions helps you write cleaner and more maintainable code.
The goal of this lesson is to refresh your memory on defining and declaring functions, understanding function overloading, and learning to call these functions effectively.
Functions: Declaration and Definition
In C++, a function must be declared before it is used. This informs the compiler about the function's name, types of inputs, and output. Function declaration is like making a promise that the actual function (function definition) will appear in the code. However, if the function is defined before it is used, there is no need for a separate declaration. The compiler will already know about the function when it encounters the function call.
Function definition provides the function's actual body. It's where the promised function does its work.
Consider these declarations and definitions in our code snippet:
The add functions return the sum of the two input parameters.
Function Overloading
C++ allows function overloading, meaning you can have multiple functions with the same name but different parameter lists. The compiler differentiates them based on the number and types of parameters.
Function overloading is useful when actions are conceptually the same but require different types or numbers of inputs. For example, you might want to add integers sometimes and doubles at other times. Overloading allows you to use the same function name (add) while handling both types.
Here’s our overloaded add function:
This shows two versions of add: one for integers and one for doubles. The compiler decides which version to call based on the provided argument types.
Using Functions in `main()`
Once functions are declared and defined, they can be called from the main() function or any other function.
Calling a function involves specifying the function name followed by arguments in parentheses.
In our code snippet, we call the add function from main():
Here, add(2, 3) calls the integer version of add, returning 5. Similarly, add(2.5, 3.5) calls the double version, returning 6.0. The results are then printed using std::cout.
