Interview Q&A · C++ · 9 questions in this topic
Functions, Overloading & Argument Passing — C++ Interview Q&A
How C++ functions really work — overloading, default arguments, inline, pass-by-value vs reference, and function pointers. Part of Functions & Lambdas · 213 questions in the C++ bank.
What is function overloading and how does the compiler choose an overload?
Answer
Function overloading lets multiple functions share a name with different parameter lists (arity or types). The compiler picks the best viable candidate through overload resolution: exact matches beat promotions, which beat standard conversions, which beat user-defined conversions.
Return type alone never distinguishes overloads, and overloads that differ only in top-level const on by-value parameters are redeclarations, not overloads.
Key points
- 1Overloads must differ in parameter count, types or (for member functions) ref/const qualifiers.
- 2Resolution order — exact match, promotion (float to double), standard conversion, user conversion, ellipsis.
- 3Ambiguous calls are compile errors, not runtime guesses.
Example
int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } add(2, 3); // int version add(2.0, 3); // double version (promotion of 3)
💡 Mention that return type is not part of the signature for overload purposes — it is the most frequently probed edge.
What are default arguments? What rules apply to them?
Answer
Default arguments supply a value when the caller omits it. They must appear trailing (no non-default parameter may follow a defaulted one in the same declaration), can only be specified once per scope (usually in the declaration, not the definition), and are bound at the call site — so changing a default in a header requires recompiling callers.
Defaults on virtual functions are especially dangerous because the default used is the static type's, while the function executed is the dynamic type's.
Example
void log(const std::string& msg, int level = 1); log("boot"); // level = 1 log("disk full", 3); // level = 3
What does `inline` actually do in modern C++?
Answer
inline is primarily a linkage directive: it allows a function (or variable, since C++17) to be defined in multiple translation units, with the linker merging them into one — which is why header-defined functions must be inline. The inlining optimization hint is secondary; the compiler inlines on its own heuristics regardless of the keyword.
So: inline solves the ODR problem for header definitions first, and suggests inlining only weakly second.
Example
// header.h #pragma once inline int square(int x) { return x * x; } inline int counter = 0; // inline variable (C++17): one shared instance
💡 Say ODR-safe header definitions first, optimization hint second — that ordering is what separates modern answers from 1990s answers.
Pass-by-value vs pass-by-reference vs pass-by-pointer — when do you use each?
Answer
Pass small trivially-copyable values (int, double, small enums) by value. Pass anything expensive or mutated via const reference (read-only) or non-const reference (out-param). Use pointers when null is a legitimate value, for reseatable indirection, or at C APIs.
Modern rule: const T& for in-params you do not copy, T for sinks you will move-from, and std::optional<T&>-style wrappers or pointers when nullability is needed (gsl::not_null documents non-null).
Example
void cheap(int x); // small value: by value void read(const std::string& s); // in-param: const ref, no copy void fill(std::vector<int>& out); // out-param: non-const ref void maybe(const int* p); // nullable: pointer (check null)
💡 One crisp line — value for cheap copies, const-ref for read-only, pointer for nullable — answers 90% of interview variants.
What is the difference between call by value and call by reference in terms of what the callee observes?
Answer
By value gives the callee an independent copy — mutations are invisible to the caller (but cost a copy). By reference (T& / const T&) aliases the caller's object — mutations are visible, and no copy occurs. By pointer is reference-with-null: same aliasing, plus explicit dereference and a null check obligation.
References cannot be null or reseated; pointers can do both, which is exactly why each exists.
Example
void by_val(int x) { x = 99; } void by_ref(int& x) { x = 99; } int n = 1; by_val(n); // n still 1 by_ref(n); // n is now 99
What are function pointers and how does `std::function` differ?
Answer
A function pointer holds the address of a free function (or static member) with an exact signature — zero overhead, but it cannot capture state. std::function is a type-erased callable wrapper that can hold free functions, lambdas (including capturing ones), functors and member bindings at the cost of potential heap allocation and indirect dispatch.
Use function pointers for C interop and the hottest callbacks; std::function for flexible callbacks; templates (or auto parameters) when you want zero-overhead genericity.
Example
int add(int a, int b) { return a + b; } int (*fp)(int, int) = &add; // function pointer #include <functional> std::function<int(int,int)> cb = add; cb = [](int a, int b) { return a * b; }; // same wrapper, capturing lambda ok
💡 State the trade-off triangle explicitly: raw pointer (fastest, no state), template/auto (fastest generic, header-only), std::function (flexible, small cost).
What is recursion, and what must every recursive C++ function have?
Answer
Recursion is a function calling itself on a smaller subproblem. Every correct recursion needs a base case that terminates and a progress guarantee that each call moves toward it. Missing either gives infinite recursion and (in practice) stack overflow.
C++ adds two practical concerns: deep recursion can overflow the fixed call stack (prefer iteration or tail-call-friendly shapes for huge n), and exponential naive recursion (like textbook Fibonacci) needs memoization or DP.
Example
long long fact(int n) { if (n <= 1) return 1; // base case return 1LL * n * fact(n - 1); // progress: n shrinks }
💡 Always say base case plus progress in one breath — interviewers listen for both halves.
What happens at runtime when a function is called (stack frames)?
Answer
The caller evaluates arguments, then the call sequence pushes the return address and creates a frame: saved registers, local variables, and temporaries. Control jumps to the callee, which tears the frame down on return and hands a value back (often in a register). Too many nested frames exhaust the stack.
This model explains locals dying at scope exit, why returning a reference to a local dangles, and why deep recursion crashes with stack overflow rather than bad_alloc.
Key points
- 1Call — arguments evaluated, return address saved, frame created.
- 2Execute — locals live in the frame; destruction runs at scope exit.
- 3Return — frame destroyed; by-value results copied/moved out or elided.
💡 Tie the frame model to the dangling-reference bug — it turns abstract stack talk into a bug you can explain.
What is the difference between `malloc/free` and `new/delete`?
Answer
malloc/free allocate raw bytes and know nothing about types or constructors; new/delete allocate memory and run constructors/destructors. new throws std::bad_alloc on failure (or returns null with std::nothrow), while malloc returns null. They must never be mixed.
In modern C++ you rarely call either directly — containers, std::string and smart pointers own the calls, which is the entire point of RAII.
Example
int* a = (int*)std::malloc(3 * sizeof(int)); // no construction std::free(a); int* b = new int[3](); // value-initialized delete[] b; // must match new[] with delete[]
Recommended resourcesAffiliate links · may earn us a commission