Definition
📌 Functions
C++ functions work like C's, but add two powerful features: default arguments (a parameter can have a fallback value) and function overloading (multiple functions can share a name if their parameter lists differ)..
Syntax
syntax
returnType functionName(type param = defaultValue) {
return value;
}Example
cpp
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int main() {
cout << add(2, 3) << endl;
cout << add(2.5, 3.5) << endl;
return 0;
}Output
output5
6
Important Points
- Overloaded functions must differ in parameter type or count, not just return type.
- Default arguments let callers omit parameters that have a sensible fallback value.
- Functions can be passed by value, by reference (
&), or by pointer. inlinefunctions can suggest to the compiler to avoid function-call overhead for small functions.
Common Mistakes
- Overloading two functions that differ only by return type — this doesn't compile.
- Giving a default value to a parameter that isn't the last one in the list.
- Forgetting that pass-by-value still copies large objects — use
const&for efficiency.
Interview Tip
🎯 Before your interview
Be ready to define function overloading precisely: same name, different parameter list, resolved at compile time.
