LearnForFree
C++ For Beginners
Lesson

Functions, Overloading & Default Arguments

A function is a self-contained, reusable block of code designed to perform a specific task. Breaking large programs into small functions makes code easier to read, test, and maintain. • Return Type: The data type of the output the function sends back. Use void if the function performs an action (like printing) without returning a value. • Parameters vs. Arguments: Parameters are the placeholder variables listed in the function definition; Arguments are the actual values passed in when calling the function. 2. Function Declaration (Prototype) vs. Definition Because C++ compiles from top to bottom, the compiler must know a function exists before you call it in main(). You can place a function prototype (just the header ending with ;) above main(), and write the full function definition below main(). 3. Default Arguments You can assign default values to parameters in the declaration. If the caller omits those arguments, the defaults are used. (Default parameters must always be placed on the rightmost side). 4. Function Overloading C++ allows multiple functions to share the exact same name as long as their parameter lists differ in either the number of parameters or the data types of parameters. The compiler automatically picks the right version based on the arguments you pass.
#include <iostream> // Function Prototypes (Declarations) int add(int a, int b); double add(double a, double b); // Overloaded function void greetUser(std::string name, std::string greeting = "Hello"); // Default argument int main() { std::cout << "Int sum: " << add(4, 5) << "\n"; // Calls int version std::cout << "Double sum: " << add(2.5, 3.7) << "\n"; // Calls double version greetUser("Alex"); // Uses default greeting "Hello" greetUser("Maria", "Welcome"); // Overrides default greeting return 0; } // Function Definitions int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } void greetUser(std::string name, std::string greeting) { std::cout << greeting << ", " << name << "!\n"; }

Watch companion video on YouTube

Sign in to save your progress