C++ Functions

Overloading, default arguments and recursion.

✍️ 2 exercises in this lesson
  • Default arguments: void greet(std::string name = "Guest")
  • Overloading: functions with the same name but different parameter types.
  • Pass by reference with & to change the caller's variable or avoid copying: void bump(int& n).
  • Use const& for large read-only arguments: void print(const std::string& s).
  • Lambdas: auto add = [](int a, int b) { return a + b; };

Key Takeaways: C++ Functions

Mastering C++ Functions helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C++ Functions Code Example

C++
#include <iostream>
#include <string>

int area(int side) { return side * side; }
double area(double r) { return 3.14159 * r * r; }

void greet(const std::string& name = "Guest") {
    std::cout << "Hello, " << name << "\n";
}

void bump(int& n) { n += 10; }

int main() {
    std::cout << area(4) << " " << area(1.0) << "\n";
    greet();
    greet("Bilal");

    int score = 5;
    bump(score);
    std::cout << score << "\n";

    auto multiply = [](int a, int b) { return a * b; };
    std::cout << multiply(6, 7) << "\n";
    return 0;
}
Output
16 3.14159
Hello, Guest
Hello, Bilal
15
42
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C++ Functions Practice Exercises

Check what you learned in “C++ Functions”.

/ 2 solved
Fill in the blank

Pass by reference so the function can change the caller's variable.

void bump(int n) { n += 10; }
✓ Correct! Not quite. Try again.
Multiple choice

What is a lambda in C++?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services