C++: Functions & Overloading
What you will learn
How to define functions with return types and parameters, how function overloading works, and why int main() is the entry point.
Defining a function
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(3, 4);
std::cout << result; // 7
return 0;
}
Syntax: return type, function name, parameters in parentheses with their types, body in curly braces.
The main function
Every C++ program must have exactly one main function — this is where execution starts. The return value is an exit code: 0 means success, non-zero means an error.
Function overloading
C++ lets you define multiple functions with the same name as long as their parameter types differ:
int max(int a, int b) {
return (a > b) ? a : b;
}
double max(double a, double b) {
return (a > b) ? a : b;
}
std::cout << max(3, 7); // calls int version
std::cout << max(3.5, 2.1); // calls double version
The compiler picks the right version based on the argument types. This is called overload resolution.
Default arguments
void greet(std::string name, std::string greeting = "Hello") {
std::cout << greeting << ", " << name << "!\n";
}
greet("Alice"); // Hello, Alice!
greet("Bob", "Hi"); // Hi, Bob!
Common mistakes
- Forgetting the semicolon after a class or struct definition (but not after a function body!)
- Writing
void main()instead ofint main()—intis the standard return type - Forgetting
return 0;at the end ofmain()— C++ allows omitting it (returns 0 implicitly), but being explicit is clearer - Overloading functions that differ only by return type — the compiler cannot distinguish them (parameter types must differ)
Quick check below!