Functions in C++ support overloading (same name, different types), default arguments, pass-by-reference, and templates for generic code.
Basic Function
CPP
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
cout << add(3, 4) << endl; // 7
return 0;
}| Part | Meaning |
|---|---|
int |
Return type |
add |
Function name |
(int a, int b) |
Parameters — each has a type |
return a + b; |
Value returned to the caller |
Default Arguments
CPP
void greet(string name, string greeting = "Hello") {
cout << greeting << ", " << name << "!" << endl;
}
greet("Sita"); // "Hello, Sita!"
greet("Sita", "Namaste"); // "Namaste, Sita!"Rule: default arguments must be at the end of the parameter list.
Pass by Reference
The & operator lets a function modify the original variable:
CPP
void doubleValue(int &n) { // & = reference
n *= 2; // modifies the original
}
int main() {
int x = 5;
doubleValue(x);
cout << x << endl; // 10 — x was modified
}Without &, the function gets a copy — changes do not affect the
original.
Function Overloading
Same name, different parameter types:
CPP
int square(int n) { return n * n; }
double square(double n) { return n * n; }
square(5); // 25 (int version)
square(3.14); // 9.8596 (double version)The compiler picks the right version based on the argument types.
Templates (Generic Functions)
Write one function that works with any type:
CPP
template <typename T>
T maximum(T a, T b) {
return (a > b) ? a : b;
}
maximum(3, 7); // 7 (int)
maximum(3.14, 2.71); // 3.14 (double)
maximum<string>("hello", "world"); // "world"Inline Functions
Small functions that the compiler copies into the call site (avoids function-call overhead):
CPP
inline int square(int n) { return n * n; }Lambda Functions (C++11+)
Anonymous functions for short, local logic:
CPP
auto add = [](int a, int b) { return a + b; };
cout << add(3, 4) << endl; // 7
// With capture — access variables from the surrounding scope
int factor = 10;
auto multiply = [factor](int n) { return n * factor; };
cout << multiply(5) << endl; // 50Tips
- Use pass-by-reference (
&) when you need to modify the original. - Use pass-by-const-reference (
const &) for large objects you do not want to copy:void print(const string &s). - Templates are the C++ way to write generic code — prefer them
over
void*or macros. - Keep functions short and focused — one function, one job.
Next: classes — object-oriented C++.