C++ Functions — Overloading, Default Args, Inline | Tutorials Logic
What is a Function?
A function is a named, reusable block of code that performs a specific task. Functions reduce repetition, improve readability, and make code easier to test and maintain.
Syntax: returnType functionName(parameters) { body }
#include <iostream>
using namespace std;
// Function declaration (prototype) - tells compiler the signature
int add(int a, int b);
void greet(string name);
int main() {
cout << add(3, 4) << endl; // 7
greet("Alice"); // Hello, Alice!
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
// void functions don't need return
}
Pass by Value vs Pass by Reference
#include <iostream>
using namespace std;
// Pass by VALUE - copy is made, original unchanged
void doubleVal(int x) {
x *= 2;
cout << "Inside: " << x << endl;
}
// Pass by REFERENCE - works on original variable
void doubleRef(int &x) {
x *= 2;
}
// Pass by CONST REFERENCE - read-only, no copy (efficient for large objects)
void printName(const string &name) {
cout << "Name: " << name << endl;
}
// Multiple return values via references
void minMax(int a, int b, int &mn, int &mx) {
mn = (a < b) ? a : b;
mx = (a > b) ? a : b;
}
int main() {
int n = 10;
doubleVal(n);
cout << "After doubleVal: " << n << endl; // 10 (unchanged)
doubleRef(n);
cout << "After doubleRef: " << n << endl; // 20 (changed!)
printName("Bob");
int lo, hi;
minMax(7, 3, lo, hi);
cout << "Min: " << lo << ", Max: " << hi << endl; // 3, 7
return 0;
}
Function Overloading and Default Arguments
#include <iostream>
using namespace std;
// Function overloading - same name, different parameter types/count
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c){ return a + b + c; }
// Default arguments - must be rightmost parameters
void greet(string name, string greeting = "Hello") {
cout << greeting << ", " << name << "!" << endl;
}
// inline function - hint to compiler to expand inline (avoids call overhead)
inline int square(int x) { return x * x; }
int main() {
cout << add(3, 4) << endl; // 7 (int version)
cout << add(1.5, 2.5) << endl; // 4.0 (double version)
cout << add(1, 2, 3) << endl; // 6 (3-arg version)
greet("Alice"); // Hello, Alice!
greet("Bob", "Hi"); // Hi, Bob!
cout << square(5) << endl; // 25
return 0;
}
Level Up Your C plus plus Skills
Master C plus plus with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related C++ Topics