Interview Q&A · C++ · 7 questions in this topic
Lambdas, auto & Callables — C++ Interview Q&A
Modern callable plumbing — lambda captures, `auto`, `std::function` vs templates, and how lambdas actually desugar. Part of Functions & Lambdas · 213 questions in the C++ bank.
What is a lambda expression and what do the capture clauses mean?
Answer
A lambda is an anonymous function object: [captures](params) specifiers -> returnType { body }. Captures control what the lambda closes over: [] nothing, [=] copy everything used, [&] reference everything used, [x] copy x, [&x] reference x, [this] the object pointer, [*this] a copy of the object (C++17).
Default captures are convenient but risky — [&] can dangle when the lambda outlives the scope, which is why explicit captures are preferred in stored callbacks.
Example
int factor = 3; auto by_copy = [factor](int x) { return x * factor; }; auto by_ref = [&factor](int x) { factor += x; return factor; }; std::vector<int> v{1,2,3}; int sum = 0; for (int x : v) sum += by_copy(x);
What does a lambda desugar to?
Answer
The compiler generates an unnamed functor class (closure type) with captured values as members and operator() as the body, plus a constructor capturing them. Each lambda expression has a unique, unnamed type — which is why you store lambdas in auto, not by naming their type.
A captureless lambda additionally provides a conversion to a plain function pointer, since it needs no state.
Example
// conceptually, [factor](int x){ return x*factor; } becomes: struct __Lambda { int factor; int operator()(int x) const { return x * factor; } };
💡 Saying each lambda has a unique unnamed type explains in one stroke why auto is the natural way to hold one.
What does `auto` do, and when should you (and should you not) use it?
Answer
auto deduces the variable's type from its initializer at compile time — no runtime cost, and often more correct than spelling the type (it cannot accidentally narrow or drop references/const the way a hand-written type can). Use it for iterators, complex template types, lambdas and range-for over containers.
Do not use it where the deduced type surprises: auto x = {1,2,3} deduces initializer_list, auto drops top-level const/ref unless you write auto& / const auto&, and auto return types need care with dangling references.
Example
std::map<std::string, std::vector<int>> m; auto it = m.find("k"); // no one wants to spell this type const auto& ref = m.at("k"); // keep const + reference! auto&& any = get_value(); // forwarding reference binds to anything
What is the difference between a functor, a lambda and `std::function`?
Answer
A functor is any class/struct with operator() — full control, inline-friendly, can hold state. A lambda is compiler-generated functor sugar. std::function is a type-erased holder for any callable with a given signature — maximally flexible (it can be reassigned across callable kinds) at the cost of indirection and possible allocation.
Performance order: template/auto generic (zero overhead) > functor/lambda direct > std::function > virtual dispatch, roughly.
Example
struct Adder { int k; int operator()(int x) const { return x + k; } }; Adder add5{5}; auto lam = [](int x) { return x * 2; }; std::function<int(int)> f = add5; f = lam; // same holder, different callable
💡 Frame it as flexibility vs cost — templates are free but fixed at compile time, std::function is flexible at a small runtime price.
What is perfect forwarding and what is `std::forward` for?
Answer
Perfect forwarding preserves a pass-through argument's value category (lvalue stays lvalue, rvalue stays rvalue) through a forwarding reference (T&& in a deduced context) plus std::forward<T>. Without it, a named parameter is always an lvalue inside the function, so moves silently degrade to copies.
The canonical pattern is a template factory: template<class T> void wrap(T&& x) { target(std::forward<T>(x)); }. Misusing std::move on a forwarding reference unconditionally casts to rvalue and can move-from an lvalue the caller still needs.
Example
template<class T> void wrapper(T&& arg) { // std::forward<T> keeps rvalues movable, lvalues safe process(std::forward<T>(arg)); }
What is the difference between a static (free) function and a member function call?
Answer
A free or static member function is called directly with no object. A non-static member function receives an implicit this pointer to the object it was called on, can be virtual (dispatching on dynamic type), and can be const/ref-qualified. Static member functions have no this, cannot be virtual or const, and are essentially namespaced free functions.
That hidden this parameter is why member pointers have their own syntax (void (C::*)()) and why non-static members cannot convert to plain function pointers.
Example
struct S { void member() {} // has implicit S* this static void st() {} // no this }; S s; s.member(); S::st(); void (S::*mp)() = &S::member; // member pointer syntax
What are `argc` and `argv` pitfalls to avoid?
Answer
argv[0] is the program name (or empty), not the first real argument — real arguments start at argv[1]. argv[argc] is null, argv strings are mutable but modifying them is rarely wise, and arguments arrive as text so numeric parsing needs stoi/stod with error handling.
Always validate the count before indexing, and prefer a span/view over argv in modern code for bounds safety.
Example
int main(int argc, char* argv[]) { if (argc < 2) return 1; // validate before use std::string first = argv[1]; // not argv[0]! }
Recommended resourcesAffiliate links · may earn us a commission