← C++ roadmap

Topic 3 of 27 · Beginner

Functions, Overloading & Lambdas

Default arguments, overloading, inline and lambda expressions.

Concept

Functions can be overloaded by parameter types and can have default arguments (from the right).

A lambda is an inline anonymous function: [capture](params) { body }. Capture by value [=] or reference [&].

Lambdas are commonly passed to STL algorithms like sort and count_if.

Code (C++20)

#include <algorithm>
#include <iostream>
#include <vector>

int area(int s) { return s * s; }
int area(int l, int w) { return l * w; }
double price(double p, double gst = 0.18) { return p * (1 + gst); }

int main() {
    std::vector<int> v{5, 2, 8, 1};
    int threshold = 3;
    auto big = std::count_if(v.begin(), v.end(), [threshold](int x) { return x > threshold; });
    std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
    std::cout << area(3) << ' ' << area(2, 5) << ' ' << big << '\n';
}

Remember

  • Overload by parameters, not return type.
  • Default args go right-to-left.
  • Capturing by reference can dangle.

Interview questions

How is overloading resolved?

At compile time, by matching argument types to parameter lists (exact match, promotion, then conversions).

What is name mangling?

The compiler encodes parameter types into symbol names so overloaded functions get unique linker names; extern "C" disables it.

Practise C++ with the AI mentor

Lesson test

Take an 8-question test on “Functions, Overloading & Lambdas” — concepts, output prediction, bug spotting and interview questions.

Can't find a C++ topic you need for exams or placements? Request it and we'll add it.