Functions & Lambdas
C++ functions extend C with: default parameters, function overloading (same name, different params), pass-by-reference, and lambda expressions for inline anonymous functions.
40 min•By Priygop Team•Last updated: Feb 2026
Functions Code
Example
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Default parameters
void greet(const string &name, const string &greeting = "Hello") {
cout << greeting << ", " << name << "!" << endl;
}
// Function overloading (same name, different params)
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
string add(const string &a, const string &b) { return a + b; }
// Pass by const reference (efficient, no copy)
void printVector(const vector<int> &v) {
for (int val : v) cout << val << " ";
cout << endl;
}
// Pass by reference (modifies original)
void doubleAll(vector<int> &v) {
for (int &val : v) val *= 2;
}
int main() {
greet("Alice"); // "Hello, Alice!"
greet("Bob", "Good morning"); // "Good morning, Bob!"
cout << add(3, 4) << endl; // int: 7
cout << add(3.5, 2.1) << endl; // double: 5.6
cout << add("Hi", " there") << endl; // string: "Hi there"
vector<int> nums = {5, 2, 8, 1, 9, 3};
printVector(nums); // 5 2 8 1 9 3
// Lambda expressions
auto square = [](int x) { return x * x; };
cout << square(5) << endl; // 25
// Lambda with capture
int multiplier = 3;
auto multiply = [multiplier](int x) { return x * multiplier; };
cout << multiply(7) << endl; // 21
// Lambda with algorithms
sort(nums.begin(), nums.end()); // Ascending
sort(nums.begin(), nums.end(), [](int a, int b) {
return a > b; // Descending
});
// for_each with lambda
for_each(nums.begin(), nums.end(), [](int n) {
cout << n << " ";
});
return 0;
}