Interview Cracker GitHub

C++ Interview Questions


🟢 Q. What is RAII, and why is it the centre of C++ resource management?

Answer. Resource Acquisition Is Initialization: bind a resource (memory, file handle, lock, socket) to an object's lifetime — acquire it in the constructor, release it in the destructor. Because destructors run deterministically when the object goes out of scope, "cleanup" stops being a thing you remember to do and becomes a thing the language does for you, on every exit path including exceptions.

The follow-ups:


🟢 Q. unique_ptr, shared_ptr, weak_ptr — when is each one right?

Answer. unique_ptr is the default: single ownership, zero overhead (same size as a raw pointer), non-copyable but movable. shared_ptr is reference-counted shared ownership — use it when you genuinely cannot decide the owner up front. weak_ptr observes a shared_ptr'd object without extending its life; lock() upgrades to a shared_ptr or gives you nothing.

The trade-offs that matter in an interview:


🟡 Q. What does "move semantics" actually do, and when does a move happen

implicitly?

Answer. A move transfers a resource from one object to another instead of copying it: the moved-from object is left valid-but-unspecified (usually empty), and the expensive copy is skipped. std::move(x) does not move anything by itself — it is a cast to rvalue reference that permits a move constructor/assignment to be selected.

The practical rules:


🟡 Q. virtual — what is the runtime cost, and what are the two traps?

Answer. A class with virtual functions gets a vtable (one per dynamic type, shared by all its instances) and each object carries a vptr; a virtual call reads the vptr and dispatches through the table — one extra indirection, and the call usually cannot be inlined. The cost is real but small; the design cost is that the type's behaviour is no longer knowable from the static type.

The two traps (both demonstrated in examples/cpp/oop/virtual_functions_and_the_vtable.cpp):

The follow-up this sets up: virtual on the first virtual call also cannot be inlined, which is why hot single-type code sometimes uses the CRTP idiom (static dispatch through templates) to buy the call back.


🔴 Q. Rule of zero, rule of three, rule of five — and how does a modern

codebase actually avoid all of them?

Answer. If a class owns a resource it must manage its five special members consistently: destructor, copy constructor, copy assignment, move constructor, move assignment. Rule of three: if you need one of the first three, you probably need all three. Rule of five: with move semantics, the count is five. Rule of zero: the best position is to need none — hold resources in types that already manage themselves (unique_ptr, string, vector) and let the implicit special members do the right thing.

Why this is the senior-level answer:

See also examples/cpp/raii/raii_and_move.cpp and examples/cpp/smart-pointers/.