Interview Q&A · C++ · 8 questions in this topic
C++ vs C and First Principles — C++ Interview Q&A
How C++ differs from C, what `cout` vs `printf` really means, static typing, and the habits that separate C written in C++ from real C++. Part of C++ Fundamentals · 213 questions in the C++ bank.
How is C++ different from C?
Answer
C++ starts from C's procedural core and adds classes and objects, references, function overloading, templates, exceptions, namespaces and a much larger standard library (STL containers, algorithms, iostreams). C++ also enforces stronger type checking — for example, implicit void* conversions allowed in C are errors in C++.
Modern guidance: C++ is not just C with classes. Idiomatic C++ prefers std::vector over raw arrays, std::string over char buffers, RAII over manual cleanup, and algorithms over hand loops.
Key points
- 1OOP — classes, inheritance, polymorphism, access control.
- 2Generics — templates vs C macros and void* tricks.
- 3Safer abstractions — references, std::string, containers, smart pointers.
- 4Stronger type system — fewer implicit conversions than C.
💡 End with one idiomatic contrast (vector vs malloc'd array) to show you write C++, not C-style code compiled as C++.
Is C++ statically or dynamically typed? What does that imply?
Answer
C++ is statically typed: every variable and expression has a type fixed at compile time, and the compiler checks conversions and operations before the program runs. Mismatches are compile errors rather than runtime surprises.
The trade-off is compile-time strictness for runtime speed and safety — no per-operation type checks in optimized builds, and templates resolve entirely at compile time. Runtime polymorphism through virtual functions is the controlled exception, dispatched via the vtable.
Example
int x = 5; // x = "hello"; // compile error: no implicit conversion Base* p = new Derived(); // static type Base*, dynamic type Derived* p->virt(); // virtual dispatch at runtime
💡 Contrast with Python's dynamic typing briefly — interviewers asking this often want to hear you understand the trade-off, not just the label.
`cout` vs `printf` — which should you use and why?
Answer
Prefer iostreams (std::cout) in C++: it is type-safe (no format-specifier mismatches), extensible via operator<< overloads, and works with user-defined types. printf is faster in some micro-benchmarks and familiar to C programmers, but a wrong %d/%s mismatch is undefined behavior that the compiler may only warn about.
For high-volume output, buffered accumulation (ostringstream or manual buffering) usually matters more than cout-vs-printf choice.
Example
#include <cstdio> #include <iostream> int main() { int n = 42; std::cout << "n=" << n << "\n"; // type-safe std::printf("n=%d\n", n); // UB if specifier mismatches type }
What is undefined behavior, and why do C++ interviews obsess over it?
Answer
Undefined behavior (UB) means the standard imposes no requirements — the program may crash, corrupt data, or appear to work. Classic causes: signed integer overflow, null/dangling pointer dereference, use-after-free, data races, use of uninitialized values, and violating strict aliasing.
Interviews obsess because optimizing compilers assume UB never happens and will optimize accordingly — so UB can make even the code before the bug misbehave, and sanitizers (ASan/UBSan) exist precisely to catch it.
Key points
- 1Unspecified behavior — valid options, implementation chooses (e.g. order of some evaluations).
- 2Implementation-defined — implementation must document its choice (e.g. sizeof(int)).
- 3Undefined — no guarantees at all; the dangerous one.
Example
int x = INT_MAX; // x + 1; // signed overflow: undefined behavior int* p = nullptr; // *p = 1; // null dereference: undefined behavior
💡 Naming ASan/UBSan as your debugging tool for UB shows production experience, not just standardese.
What is the difference between C-style strings, `std::string` and string views?
Answer
C-style strings are null-terminated char arrays — manual length tracking, easy buffer overflows, owned by convention only. std::string owns a resizable character buffer with value semantics. std::string_view (C++17) is a non-owning read-only window over contiguous characters — cheap to copy, but it must never outlive the data it views.
Rule of thumb: std::string for ownership/storage, std::string_view for read-only parameters over existing text, C strings only at system boundaries.
Example
#include <string> #include <string_view> void log(std::string_view msg); // accepts string, literal, view — no copy std::string owner = "hello"; log(owner); log("literal"); // std::string_view bad = std::string("temp"); // dangles!
What are header files for, and what belongs in them?
Answer
Headers declare the interface other translation units need: class definitions, function declarations, inline/template definitions, constants and macros. They should not contain non-inline function definitions or non-inline variable definitions, or every includer will violate the One Definition Rule at link time.
Modern headers are self-contained (include what they use), guarded (#pragma once or #ifndef guards), and minimal (forward-declare where a full definition is not needed).
Example
// widget.h — interface only #pragma once #include <string> class Widget { public: explicit Widget(std::string name); void rename(std::string n); private: std::string name_; };
💡 Saying headers are for interfaces and .cpp files are for implementations is the one-line answer; the ODR constraint is the depth.
What does `static` mean in C++? (It has four meanings.)
Answer
static is context-dependent: on a file-scope variable/function it means internal linkage (visible only in that translation unit); on a local variable it means static storage duration (persists across calls); on a class member it means shared by all instances; on a class member function it means callable without an object (no this).
Interviewers ask this precisely because one keyword does four jobs — naming the context for each meaning is the whole answer.
Key points
- 1File scope — internal linkage: private to this .cpp file.
- 2Local variable — persists across calls, initialized once.
- 3Class member variable — one shared instance, defined once outside the class (pre-C++17).
- 4Class member function — no this pointer, cannot be virtual or const.
Example
// file scope: only this TU sees it static int file_counter = 0; struct S { static int shared; // one per class, not per object static int make() { return ++shared; } }; int S::shared = 0;
💡 Enumerate all four without prompting — stopping after one or two is the common failure mode for this question.
What is the difference between `struct` and `class`?
Answer
Technically only the default access differs: struct members and bases are public by default, class members and bases are private by default. Everything else — constructors, methods, inheritance, templates — works identically.
By convention, struct signals a passive data bundle (often with all-public members), while class signals an encapsulated type with invariants. Plain-data structs intended for C compatibility should stay POD-like (no virtuals, no complex constructors).
Example
struct Point { double x, y; }; // public by default class Widget { int state_ = 0; // private by default public: void reset() { state_ = 0; } };
Recommended resourcesAffiliate links · may earn us a commission