C++ quiz – 45 questions with answers
Try it interactively
With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.
Beginner (15 questions)
How do you print text to the console in C++?
- std::cout << "Hi";
- print("Hi");
- System.out.println("Hi");
- echo "Hi";
Show answer
Correct: std::cout << "Hi";
std::cout from <iostream> is the standard output stream; you push values into it with <<.
What does this code print?
#include <iostream>
int main() {
std::cout << 7 / 2 << " " << 7 % 2;
}- 3.5 1
- 3 1
- 4 1
- 3 0
Show answer
Correct: 3 1
With int divided by int, integer division is used: 7 / 2 = 3, and the remainder 7 % 2 is 1.
What value does d have after double d = 7 / 2;?
- 3.5
- 3
- 4
- Compile error
Show answer
Correct: 3
The division 7 / 2 is first evaluated as int (= 3) and only then converted to double. Write 7 / 2.0 for 3.5.
What does this code print?
#include <iostream>
int main() {
int x = 5;
x += 3;
++x;
std::cout << x;
}- 8
- 9
- 10
- 5
Show answer
Correct: 9
x += 3 gives 8, ++x increases it to 9.
What does this code print?
#include <iostream>
int main() {
int a = 10;
int& r = a;
r = 20;
std::cout << a;
}- 10
- 20
- 30
- Compile error
Show answer
Correct: 20
r is just another name for a. The assignment via r therefore changes a.
Which header is needed for std::cout?
- <stdio.h>
- <string>
- <iostream>
- <cstdlib>
Show answer
Correct: <iostream>
std::cout and std::cin are declared in <iostream>.
What does this code print?
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3};
v.push_back(4);
std::cout << v.size() << v[3];
}- 34
- 44
- 43
- Compile error
Show answer
Correct: 44
After push_back(4), the vector has 4 elements (size() == 4), and v[3] is the last element, i.e. 4: output "44".
What does the keyword const do for a variable?
- It is read faster
- It must not be changed after initialization
- It lives on the heap
- It is deleted automatically
Show answer
Correct: It must not be changed after initialization
const forbids changes after initialization; the compiler reports every attempt as an error.
What does this code print?
#include <iostream>
int main() {
for (int i = 0; i < 3; ++i)
std::cout << i;
}- 123
- 012
- 0123
- 321
Show answer
Correct: 012
The loop runs for i = 0, 1, 2 (condition i < 3).
What is the difference between 'A' and "A"?
- No difference
- 'A' is a single char, "A" is a text literal (with terminating character \0)
- "A" is a char, 'A' is a std::string
- 'A' is a pointer
Show answer
Correct: 'A' is a single char, "A" is a text literal (with terminating character \0)
Single quotes yield a char, double quotes a string literal (const char[2], i.e. 'A' plus the terminating character).
What does this code print?
#include <iostream>
#include <string>
int main() {
std::string s = "Hello";
std::cout << s.size() << s[1];
}- 5H
- 5e
- 4e
- 6e
Show answer
Correct: 5e
"Hello" has 5 characters; s[1] is the second character, an "e".
How do you pass a large std::string to a function that should only read it?
- By value: void f(std::string s)
- By const reference: void f(const std::string& s)
- As void*
- By reference without const, to make it faster
Show answer
Correct: By const reference: void f(const std::string& s)
const& avoids the copy and promises not to change the string – the standard for large, read-only parameters.
What does this code print?
#include <iostream>
int main() {
std::cout << -7 / 2 << " " << -7 % 2;
}- -4 1
- -3 -1
- -3 1
- -4 -1
Show answer
Correct: -3 -1
Since C++11, integer division rounds toward 0: -7 / 2 = -3. The remainder has the sign of the dividend: -7 % 2 = -1.
What does nullptr mean?
- The numeric value 0 as an int
- A pointer that points to no object
- A deleted object
- An empty string
Show answer
Correct: A pointer that points to no object
nullptr is the type-safe null pointer literal. It replaces NULL and 0 as a pointer value.
What happens when you read an uninitialized local int variable?
- It is always 0
- The value is indeterminate – undefined behavior
- The compiler sets it to -1
- An exception is thrown automatically
Show answer
Correct: The value is indeterminate – undefined behavior
Local basic types are not initialized automatically. Accessing garbage values is undefined behavior – always initialize (int x{};).
Intermediate (15 questions)
What does this code print?
#include <iostream>
struct A {
A() { std::cout << "a"; }
~A() { std::cout << "~a"; }
};
int main() {
A x;
{ A y; }
std::cout << "m";
}- aa~am~a
- a~aam~a
- aam~a~a
- aa~a~am
Show answer
Correct: aa~am~a
x is created ("a"), y is created ("a") and destroyed at the end of the block ("~a"), then "m", and at the end of main, x is destroyed ("~a"). Objects are destroyed in reverse order.
What does this code print?
#include <iostream>
#include <string>
struct Tier {
virtual std::string laut() const { return "?"; }
virtual ~Tier() = default;
};
struct Hund : Tier {
std::string laut() const override { return "Woof"; }
};
int main() {
Hund h;
Tier t = h;
const Tier& r = h;
std::cout << t.laut() << r.laut();
}- WoofWoof
- ?Woof
- Woof?
- ??
Show answer
Correct: ?Woof
Tier t = h; copies only the Tier part (slicing), so t is a plain Tier ("?"). The reference r remains a Hund and calls Hund::laut virtually ("Woof").
Why does a polymorphic base class need a virtual destructor?
- So that the compiler compiles faster
- So that when deleting through a base pointer, the destructor of the derived class also runs
- So that the class cannot be copied
- So that methods may be
const
Show answer
Correct: So that when deleting through a base pointer, the destructor of the derived class also runs
Without a virtual destructor, delete basePointer on a derived object is undefined behavior; the derived part is not destroyed correctly.
What is the problem with this code?
#include <memory>
int main() {
auto a = std::make_unique<int>(1);
auto b = a;
}- Memory leak
- Compile error: unique_ptr is not copyable
- Runtime error when accessing b
- No problem, b and a share the object
Show answer
Correct: Compile error: unique_ptr is not copyable
unique_ptr has exactly one owner, so the copy constructor is deleted. Moving works with std::move(a).
What does this code print?
#include <iostream>
#include <memory>
int main() {
auto a = std::make_shared<int>(5);
auto b = a;
auto c = std::move(a);
std::cout << b.use_count();
}- 1
- 2
- 3
- 0
Show answer
Correct: 2
b and c share the object (counter 2). a was emptied by std::move and no longer counts.
What does this code print?
#include <iostream>
int main() {
int x = 1;
auto f = [x]() { return x; };
x = 5;
std::cout << f();
}- 5
- 1
- 0
- Compile error
Show answer
Correct: 1
[x] captures x by copy at the time the lambda is created (1). Only [&x] would see the later change (5).
What does this code print?
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> m;
m["a"];
std::cout << m.size() << m["a"];
}- 00
- 10
- 11
- Runtime error
Show answer
Correct: 10
Even m["a"] alone creates the key with the default value 0. Afterwards the size is 1 and the value is 0: output "10".
What does this code print?
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4, 5, 6};
v.erase(std::remove_if(v.begin(), v.end(),
[](int x) { return x % 2 == 0; }), v.end());
for (int x : v) std::cout << x;
}- 246
- 135
- 123456
- 13
Show answer
Correct: 135
remove_if moves the elements to keep (the odd ones) to the front, erase cuts off the rest: 1, 3, 5.
What is the problem with this code?
std::vector<int> v{1, 2, 3};
for (int x : v)
if (x == 2) v.push_back(4);- Nothing, this is valid
- Undefined behavior: push_back can invalidate iterators
- The compiler forbids push_back in a loop
- x is a copy and must not be compared
Show answer
Correct: Undefined behavior: push_back can invalidate iterators
The range-for loop holds iterators. push_back can move the memory (reallocation) and invalidates them – undefined behavior.
What is the problem with this class?
struct P {
int b;
int a;
P(int v) : a(v), b(a + 1) {}
};- It does not compile
- b is initialized before a and therefore reads an uninitialized value
- a and b have the same type
- The constructor must be explicit
Show answer
Correct: b is initialized before a and therefore reads an uninitialized value
Members are initialized in the order of declaration (b before a), not in the order of the initializer list. b(a + 1) reads an a that has not been initialized yet.
What is the problem with this class?
class Zaehler {
int n_ = 0;
public:
int get() const { return ++n_; }
};- The member n_ must be public
- Compile error: a const method must not modify a member
- get must not return a value
- ++n_ is invalid syntax
Show answer
Correct: Compile error: a const method must not modify a member
In a const method, this is a pointer to const – ++n_ modifies a member and is rejected. It would only be allowed with mutable.
What is explicit for on a constructor with one parameter?
- The constructor becomes faster
- It prevents implicit conversions to this type
- It makes the class abstract
- It prevents copying
Show answer
Correct: It prevents implicit conversions to this type
Without explicit, e.g. Konto k = 5; would be allowed. With explicit, the call must be made explicitly.
How do you catch exceptions correctly?
- catch (std::exception e)
- catch (const std::exception& e)
- catch (std::exception* e)
- catch (std::exception&& e)
Show answer
Correct: catch (const std::exception& e)
By const&, nothing is copied and nothing is sliced (slicing), so derived exception types are preserved.
What does the keyword override do?
- It makes a method virtual
- The compiler checks that a virtual base class method is really being overridden
- It forbids further overriding
- It makes a method static
Show answer
Correct: The compiler checks that a virtual base class method is really being overridden
If there is a typo in the name or signature (e.g. a missing const), override produces a compile error instead of silently creating a new method.
What distinguishes std::map from std::unordered_map?
- map is sorted (lookup O(log n)), unordered_map uses hashing (O(1) on average)
- map is faster and unsorted
- unordered_map only stores numbers
- There is no difference
Show answer
Correct: map is sorted (lookup O(log n)), unordered_map uses hashing (O(1) on average)
std::map is a search tree with sorted keys, std::unordered_map a hash table with no order but usually faster access.
Advanced (15 questions)
What is the state of an object after std::string b = std::move(a);?
- a is destroyed
- a is valid, but in an unspecified state
- a is guaranteed to be the empty string
- a and b share the memory
Show answer
Correct: a is valid, but in an unspecified state
A moved-from object is valid (assigning and destroying are allowed), but its contents are unspecified. Do not rely on the old value.
What does std::move actually do?
- It moves memory on the heap
- It merely casts an object to an rvalue reference and thereby permits moving
- It deletes the object
- It copies and destroys the original
Show answer
Correct: It merely casts an object to an rvalue reference and thereby permits moving
std::move is a pure cast (static_cast<T&&>). The actual moving is done by the move constructor or move assignment of the target.
What is the problem with this code?
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string_view sv = std::string("hello");
std::cout << sv;
}- string_view cannot be printed with cout
- The temporary std::string is destroyed, sv points into nothing (undefined behavior)
- A #include <cstring> is missing
- string_view copies the text and needs too much memory
Show answer
Correct: The temporary std::string is destroyed, sv points into nothing (undefined behavior)
string_view does not own the text. The temporary std::string dies at the end of the statement, after which sv is dangling.
Which statement about the Rule of Zero is correct?
- You should write all five special functions yourself
- Classes should hold their resources in self-managing members and not define special functions themselves
- Classes must not have members
- You should always delete destructors
Show answer
Correct: Classes should hold their resources in self-managing members and not define special functions themselves
With members such as std::vector, std::string or std::unique_ptr, the compiler generates correct copying, moving and destruction automatically.
Why is return std::move(lokal); usually bad for a local variable?
- It does not compile
- It prevents copy elision (RVO) and can therefore be slower
- It deletes the variable twice
- It is undefined behavior
Show answer
Correct: It prevents copy elision (RVO) and can therefore be slower
With return lokal;, the compiler may construct the object directly at the destination (RVO) or move it implicitly. The explicit std::move prevents the elision.
What happens with this call?
template <typename T>
T add(T a, T b) { return a + b; }
auto r = add(1, 2.5);- Result 3.5 (double)
- Result 3 (int)
- Compile error: contradictory deduction of T (int and double)
- Runtime error
Show answer
Correct: Compile error: contradictory deduction of T (int and double)
The compiler deduces T from both arguments and finds int and double. Solution: add<double>(1, 2.5) or two template parameters.
What does this code print?
#include <iostream>
constexpr int f(int n) { return n < 2 ? 1 : n * f(n - 1); }
static_assert(f(5) == 120);
int main() { std::cout << f(4); }- 120
- 24
- 4
- Compile error because of static_assert
Show answer
Correct: 24
f is a constexpr factorial: f(5) == 120 is checked at compile time, and at runtime f(4) = 4 * 3 * 2 * 1 = 24 is printed.
What is the problem with this function?
auto mache() {
int x = 42;
return [&x] { return x; };
}- Lambdas must not be returned
- The lambda captures x by reference, x is destroyed after the return: calling the lambda is undefined behavior
- auto is forbidden as a return type
- x must be const
Show answer
Correct: The lambda captures x by reference, x is destroyed after the return: calling the lambda is undefined behavior
[&x] stores only a reference to the local variable. After the return, it is dangling. Solution: capture by copy ([x]).
What does this code print?
#include <iostream>
template <typename... T>
auto f(T... a) { return (a - ...); }
int main() { std::cout << f(10, 3, 2); }- 5
- 9
- 15
- -1
Show answer
Correct: 9
(a - ...) is a right fold: 10 - (3 - 2) = 9. A left fold (... - a) would give (10 - 3) - 2 = 5.
What does this code print?
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4};
auto sq = v | std::views::transform([](int x) { return x * x; });
v[0] = 10;
std::cout << *sq.begin();
}- 1
- 100
- 10
- Compile error
Show answer
Correct: 100
Views are lazy: the transformation is applied only on access. Since v[0] was set to 10 beforehand, *sq.begin() yields 100.
What does this code print?
#include <iostream>
struct M {
const char* n;
M(const char* nm) : n(nm) { std::cout << n; }
~M() { std::cout << n; }
};
struct H {
M a{"a"};
M b{"b"};
};
int main() { H h; }- abab
- abba
- baab
- aabb
Show answer
Correct: abba
Members are constructed in declaration order (a, b) and destroyed in reverse order (b, a): "abba".
What is the problem here?
#include <thread>
int zaehler = 0;
void arbeite() { for (int i = 0; i < 1000; ++i) ++zaehler; }
int main() {
std::thread t1(arbeite), t2(arbeite);
t1.join(); t2.join();
}- join must not be called twice
- Data race on zaehler: undefined behavior – std::atomic or a mutex is needed
- Threads must not read global variables
- A #include <iostream> is missing
Show answer
Correct: Data race on zaehler: undefined behavior – std::atomic or a mutex is needed
Two threads write the same variable without synchronization – that is a data race and therefore UB. Solution: std::atomic<int> or std::mutex.
What is std::weak_ptr for?
- As a faster unique_ptr
- To observe an object managed by shared_ptr without increasing the reference counter (e.g. against cycles)
- To free memory manually
- To copy objects between threads
Show answer
Correct: To observe an object managed by shared_ptr without increasing the reference counter (e.g. against cycles)
weak_ptr does not count. With lock(), you get a shared_ptr, or an empty one if the object has already been destroyed. This avoids ownership cycles.
Why should move constructors be noexcept?
- So that they compile faster
- Because std::vector only moves when growing if they are, otherwise it copies for safety reasons
- Because otherwise they must not be called
- So that they are not inherited from base classes
Show answer
Correct: Because std::vector only moves when growing if they are, otherwise it copies for safety reasons
std::vector uses std::move_if_noexcept when relocating. If the move can throw, it prefers to copy in order to keep the strong exception guarantee – which costs performance.
What applies to overflow with int and unsigned int?
- Both overflow in a defined way
- Only for signed int is overflow undefined behavior; unsigned wraps modulo 2^n
- Only for unsigned is overflow UB
- Both raise an exception
Show answer
Correct: Only for signed int is overflow undefined behavior; unsigned wraps modulo 2^n
For signed integers, overflow is UB (the optimizer may rule it out). Unsigned types compute in a defined way modulo 2^n.