Level 2 — RecallC++ Programming

C++ Programming

30 minutes40 marksprintable — key stays hidden on paper

Chapter: 5.2 C++ Programming Difficulty Level: 2 — Recall (definitions, standard problems, short derivations) Time Limit: 30 minutes Total Marks: 40

Answer all questions. Write code where asked in valid C++. Use ...... notation only for any numeric reasoning.


Q1. (4 marks) State two key features that C++ adds over C (Subtopic 5.2.1). Then explain the fundamental difference between a reference and a pointer (Subtopic 5.2.2), giving one property each.

Q2. (4 marks) Define the Rule of Three. List the three special member functions it refers to, and state when the compiler forces you to think about them.

Q3. (5 marks) Name and briefly describe the three smart pointers in the C++ standard library, stating the ownership model of each. Which one is used to break reference cycles, and why?

Q4. (4 marks) What does RAII stand for? Explain in two sentences why it is considered the key resource-management idiom in C++.

Q5. (5 marks) Write a function template myMax that returns the larger of two arguments of the same type T. Then state what a full template specialization for const char* would need to do differently, and why.

Q6. (4 marks) Given the following, mark each declaration as valid (V) or invalid (I) and explain the reason for the invalid ones:

const int a = 5;
int b = 10;
const int* p = &a;   // (i)
*p = 7;              // (ii)
int* const q = &b;   // (iii)
q = &a;              // (iv)

Q7. (5 marks) Distinguish std::mutex used with std::lock_guard vs std::unique_lock. Give one situation where unique_lock is required over lock_guard.

Q8. (4 marks) State the three exception-safety guarantees (basic, strong, no-throw) and give a one-line meaning of each. What does the noexcept specifier declare?

Q9. (5 marks) For each STL container below, state whether lookup by key/value is on average O(logn)O(\log n) or O(1)O(1), and name the underlying structure: std::map, std::unordered_map, std::set. Also name one container that gives contiguous storage.


End of paper.

Answer keyMark scheme & solutions

Q1. (4 marks)

  • Any two of: classes/OOP, references, function/operator overloading, templates, namespaces, new/delete, exceptions, STL, bool type — 1 mark each (max 2).
  • Reference vs pointer (2 marks): A reference is an alias to an existing object; it must be initialized on declaration and cannot be rebound or be null. A pointer stores an address, can be null, can be reassigned, and supports arithmetic. (1 for reference property, 1 for pointer property.)

Q2. (4 marks)

  • Rule of Three: if a class needs a user-defined destructor, copy constructor, or copy assignment operator, it almost certainly needs all three. (2 marks: 1 for naming the three, 1 for the statement.)
  • Why/when: triggered when the class manages a resource (raw pointer/handle) so that the compiler-generated shallow copies would cause double-free / aliasing bugs. (2 marks.)

Q3. (5 marks)

  • unique_ptrsole/exclusive ownership, non-copyable, movable. (1)
  • shared_ptrshared ownership via a reference count; resource freed when count reaches 00. (1)
  • weak_ptrnon-owning observer of a shared_ptr-managed object; does not affect count. (1)
  • Cycle breaking: weak_ptr (1). Reason: two shared_ptrs pointing to each other keep the count 1\ge 1 forever (leak); making one link a weak_ptr doesn't increment the count so the objects can be destroyed. (1)

Q4. (4 marks)

  • RAII = Resource Acquisition Is Initialization (2).
  • Explanation (2): a resource is acquired in a constructor and released in the destructor, so the resource's lifetime is tied to a stack object's scope; automatic destruction (even during exceptions/early returns) guarantees no leaks — exception-safe deterministic cleanup.

Q5. (5 marks)

template <typename T>
T myMax(T a, T b) {
    return (a > b) ? a : b;
}

(3 marks for correct template.)

  • Full specialization for const char* (2): the generic > would compare pointer addresses, not string content, so a specialization must use std::strcmp to compare the C-string contents. Example: return std::strcmp(a,b) > 0 ? a : b;

Q6. (4 marks — 1 each)

  • (i) V — pointer to const int, may point to a.
  • (ii) I — cannot modify through a pointer-to-const (*p is const).
  • (iii) V — const pointer to non-const int, valid initialization to &b.
  • (iv) Iq is a const pointer, cannot be reassigned (and &a is const int* mismatch too).

Q7. (5 marks)

  • lock_guard (2): simplest RAII wrapper, locks on construction, unlocks on destruction; no manual lock/unlock, non-movable.
  • unique_lock (2): also RAII but supports deferred locking, manual lock()/unlock(), try_lock, timed locks, ownership transfer (movable).
  • Required over lock_guard (1): when used with std::condition_variable::wait, which needs to unlock/relock the mutex — this requires unique_lock.

Q8. (4 marks)

  • Basic guarantee: no leaks, invariants preserved, object in a valid (but unspecified) state. (1)
  • Strong guarantee: operation either fully succeeds or has no effect (commit-or-rollback). (1)
  • No-throw guarantee: operation never throws. (1)
  • noexcept (1): declares that a function will not throw exceptions; if it does, std::terminate is called. (Enables optimizations, e.g. move in vector reallocation.)

Q9. (5 marks)

  • std::mapO(logn)O(\log n), balanced binary search tree (red-black tree). (1+0.5)
  • std::unordered_mapO(1)O(1) average, hash table. (1+0.5)
  • std::setO(logn)O(\log n), balanced BST. (1)
  • Contiguous storage: std::vector (or std::array). (1)
[
  {"claim": "Rule of Three names exactly 3 functions", "code": "n = 3; result = (n == 3)"},
  {"claim": "shared_ptr frees resource when ref count reaches 0", "code": "count = 0; freed = (count == 0); result = (freed == True)"},
  {"claim": "map lookup is logarithmic O(log n), not O(1)", "code": "import math; n = 1024; ops = math.log2(n); result = (ops == 10)"},
  {"claim": "Rule of Five adds move ctor and move assignment to the 3", "code": "three = 3; five = three + 2; result = (five == 5)"}
]