Functions group reusable logic. C++ supports overloading (same name, different parameters), default arguments, and inline hints—features beyond C.
Overloading and defaults
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
void greet(const std::string& name = "world") {
std::cout << "Hello, " << name << "\n";
}
Return types
Return by value for small types; return const T& only when referring to existing storage with stable lifetime—never return references to locals.
Important interview questions and answers
- Q: Overload resolution?
A: Compiler picks the best match by parameter types at compile time—no runtime dispatch unlessvirtual. - Q: Default argument rules?
A: Defaults must be trailing; specify in declaration (often header) consistently.
Self-check
- Can two functions share a name if parameters differ?
- Why not return a reference to a local variable?
Pitfall: Never return references or pointers to local variables—undefined behavior when the stack frame ends.
Interview prep
- Function overloading?
Same function name with different parameter lists—resolved at compile time.
- Return reference to local?
Undefined behavior—the local is destroyed when the function returns.