C++C++

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++?

  1. std::cout << "Hi";
  2. print("Hi");
  3. System.out.println("Hi");
  4. 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;
}
  1. 3.5 1
  2. 3 1
  3. 4 1
  4. 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;?

  1. 3.5
  2. 3
  3. 4
  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;
}
  1. 8
  2. 9
  3. 10
  4. 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;
}
  1. 10
  2. 20
  3. 30
  4. 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?

  1. <stdio.h>
  2. <string>
  3. <iostream>
  4. <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];
}
  1. 34
  2. 44
  3. 43
  4. 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?

  1. It is read faster
  2. It must not be changed after initialization
  3. It lives on the heap
  4. 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;
}
  1. 123
  2. 012
  3. 0123
  4. 321
Show answer

Correct: 012

The loop runs for i = 0, 1, 2 (condition i < 3).

What is the difference between 'A' and "A"?

  1. No difference
  2. 'A' is a single char, "A" is a text literal (with terminating character \0)
  3. "A" is a char, 'A' is a std::string
  4. '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];
}
  1. 5H
  2. 5e
  3. 4e
  4. 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?

  1. By value: void f(std::string s)
  2. By const reference: void f(const std::string& s)
  3. As void*
  4. 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;
}
  1. -4 1
  2. -3 -1
  3. -3 1
  4. -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?

  1. The numeric value 0 as an int
  2. A pointer that points to no object
  3. A deleted object
  4. 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?

  1. It is always 0
  2. The value is indeterminate – undefined behavior
  3. The compiler sets it to -1
  4. 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";
}
  1. aa~am~a
  2. a~aam~a
  3. aam~a~a
  4. 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();
}
  1. WoofWoof
  2. ?Woof
  3. Woof?
  4. ??
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?

  1. So that the compiler compiles faster
  2. So that when deleting through a base pointer, the destructor of the derived class also runs
  3. So that the class cannot be copied
  4. 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;
}
  1. Memory leak
  2. Compile error: unique_ptr is not copyable
  3. Runtime error when accessing b
  4. 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. 1
  2. 2
  3. 3
  4. 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();
}
  1. 5
  2. 1
  3. 0
  4. 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"];
}
  1. 00
  2. 10
  3. 11
  4. 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;
}
  1. 246
  2. 135
  3. 123456
  4. 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);
  1. Nothing, this is valid
  2. Undefined behavior: push_back can invalidate iterators
  3. The compiler forbids push_back in a loop
  4. 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) {}
};
  1. It does not compile
  2. b is initialized before a and therefore reads an uninitialized value
  3. a and b have the same type
  4. 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_; }
};
  1. The member n_ must be public
  2. Compile error: a const method must not modify a member
  3. get must not return a value
  4. ++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?

  1. The constructor becomes faster
  2. It prevents implicit conversions to this type
  3. It makes the class abstract
  4. 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?

  1. catch (std::exception e)
  2. catch (const std::exception& e)
  3. catch (std::exception* e)
  4. 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?

  1. It makes a method virtual
  2. The compiler checks that a virtual base class method is really being overridden
  3. It forbids further overriding
  4. 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?

  1. map is sorted (lookup O(log n)), unordered_map uses hashing (O(1) on average)
  2. map is faster and unsorted
  3. unordered_map only stores numbers
  4. 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);?

  1. a is destroyed
  2. a is valid, but in an unspecified state
  3. a is guaranteed to be the empty string
  4. 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?

  1. It moves memory on the heap
  2. It merely casts an object to an rvalue reference and thereby permits moving
  3. It deletes the object
  4. 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;
}
  1. string_view cannot be printed with cout
  2. The temporary std::string is destroyed, sv points into nothing (undefined behavior)
  3. A #include <cstring> is missing
  4. 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?

  1. You should write all five special functions yourself
  2. Classes should hold their resources in self-managing members and not define special functions themselves
  3. Classes must not have members
  4. 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?

  1. It does not compile
  2. It prevents copy elision (RVO) and can therefore be slower
  3. It deletes the variable twice
  4. 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);
  1. Result 3.5 (double)
  2. Result 3 (int)
  3. Compile error: contradictory deduction of T (int and double)
  4. 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); }
  1. 120
  2. 24
  3. 4
  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; };
}
  1. Lambdas must not be returned
  2. The lambda captures x by reference, x is destroyed after the return: calling the lambda is undefined behavior
  3. auto is forbidden as a return type
  4. 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); }
  1. 5
  2. 9
  3. 15
  4. -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. 1
  2. 100
  3. 10
  4. 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; }
  1. abab
  2. abba
  3. baab
  4. 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();
}
  1. join must not be called twice
  2. Data race on zaehler: undefined behavior – std::atomic or a mutex is needed
  3. Threads must not read global variables
  4. 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?

  1. As a faster unique_ptr
  2. To observe an object managed by shared_ptr without increasing the reference counter (e.g. against cycles)
  3. To free memory manually
  4. 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?

  1. So that they compile faster
  2. Because std::vector only moves when growing if they are, otherwise it copies for safety reasons
  3. Because otherwise they must not be called
  4. 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?

  1. Both overflow in a defined way
  2. Only for signed int is overflow undefined behavior; unsigned wraps modulo 2^n
  3. Only for unsigned is overflow UB
  4. 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.