Unit 6: Handling Exceptions, Templates and STL - Practice Quiz

CAP455 — Object Oriented Programming Using C++ 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is the main purpose of exception handling in C++?

Basics of exception handling Easy
A. To handle runtime errors
B. To create header files
C. To overload operators
D. To declare data members

2 Which C++ feature is commonly used to handle exceptional conditions?

Basics of exception handling Easy
A. try-catch blocks
B. if-else blocks
C. switch statements
D. for loops

3 Which block contains code that may generate an exception?

Exception handling mechanism Easy
A. finally block
B. catch block
C. default block
D. try block

4 What happens when an exception is thrown in a try block?

Exception handling mechanism Easy
A. A matching handler is searched
B. The compiler deletes the block
C. The program always continues normally
D. The exception becomes a comment

5 Which keyword is used to explicitly generate an exception in C++?

Throwing exception mechanism Easy
A. raise
B. throws
C. throw
D. exception

6 Which statement correctly throws the integer value ?

Throwing exception mechanism Easy
A. raise 5;
B. catch 5;
C. try 5;
D. throw 5;

7 Which keyword introduces an exception handler?

Catching exception mechanism Easy
A. rescue
B. error
C. handle
D. catch

8 What does catch(...) match in C++?

Catching exception mechanism Easy
A. Only string exceptions
B. Any exception type
C. Only integer exceptions
D. Only standard exceptions

9 Which statement re-throws the currently handled exception?

Re-throwing an exception Easy
A. throw();
B. catch;
C. rethrow;
D. throw;

10 Why might a function re-throw an exception?

Re-throwing an exception Easy
A. To remove all program errors
B. To prevent every handler from running
C. To let another handler process it
D. To convert it into a loop

11 What is the main purpose of a function template?

Function template Easy
A. To write type-independent functions
B. To prevent function overloading
C. To define only integer functions
D. To reserve permanent memory

12 Which keyword commonly declares a template parameter in C++?

Function template Easy
A. generic
B. typename
C. templateType
D. parameter

13 What does a class template provide?

Class template Easy
A. A replacement for constructors
B. A fixed class for one object
C. A blueprint for generic classes
D. A method for handling exceptions

14 Which syntax creates an object of a class template using int as its type?

Class template Easy
A. Box b<int>();
B. template Box b<int>;
C. Box(int) b;
D. Box<int> b;

15 What can a class template be used as in inheritance?

Class template and inheritance Easy
A. Only a preprocessor macro
B. A base class
C. Only a namespace
D. Only a local variable

16 What is the Standard Template Library mainly known for providing?

Introduction and importance of Standard Template Library (STL) Easy
A. Operating system drivers
B. Graphical user interfaces
C. Reusable containers and algorithms
D. Database connection protocols

17 What is an STL container used for?

Containers Easy
A. Declaring namespaces
B. Compiling source code
C. Storing collections of objects
D. Catching only exceptions

18 Which STL component provides operations such as sorting and searching?

Algorithms Easy
A. Preprocessors
B. Constructors
C. Algorithms
D. Namespaces

19 What is the main role of an STL iterator?

Iterators Easy
A. To handle compiler warnings
B. To traverse container elements
C. To allocate class objects
D. To define template parameters

20 Which statement best describes an STL vector?

Vector container Easy
A. A fixed-size function
B. A template declaration keyword
C. A linked error handler
D. A dynamically sized array

21 What happens to local automatic objects when an exception leaves the function in which those objects were created?

Basics of exception handling Medium
A. Their destructors are called during stack unwinding
B. Their destructors run only if the exception is caught locally
C. Their constructors are called again by the handler
D. Their memory remains allocated until program termination

22 Given class Derived : public Base {};, which ordering of handlers correctly allows a Derived exception to receive specialized handling?

Exception handling mechanism Medium
A. catch(...) before catch(Derived& d)
B. catch(Derived& d) before catch(Base& b)
C. catch(Base b) followed by catch(Base& b)
D. catch(Base& b) before catch(Derived& d)

23 Consider double x = -2.0; if (x < 0) throw x;. Which handler directly matches the type of the thrown exception?

Throwing exception mechanism Medium
A. catch(long value)
B. catch(double value)
C. catch(float value)
D. catch(int value)

24 Why is catch(const std::exception& e) generally preferred to catch(std::exception e)?

Catching exception mechanism Medium
A. It avoids slicing and unnecessary copying
B. It converts every exception into std::exception
C. It prevents stack unwinding from taking place
D. It automatically retries the failed statement

25 Inside a catch block, which statement rethrows the currently handled exception while preserving its original exception object?

Re-throwing an exception Medium
A. throw;
B. catch;
C. throw e;
D. return;

26 For template<class T> T maximum(T a, T b);, what happens when maximum(4, 6.5) is called without explicit template arguments?

Function template Medium
A. T is deduced as int because the first argument determines it
B. T is deduced as double through automatic numeric promotion
C. Template argument deduction fails because the arguments imply different types
D. Two specializations are generated and their results are compared

27 Given template<class T> T square(T x) { return x * x; }, what is the type of the result of square<double>(3)?

Function template Medium
A. float
B. int
C. double
D. long

28 A class template Counter<T> contains static int count;. What is true of Counter<int>::count and Counter<double>::count?

Class template Medium
A. They refer to one shared static member
B. Both members must always contain equal values
C. Only the first specialization has the member
D. They are separate static members

29 For template<class T> class Box { T value; };, which declaration creates an object whose value member has type std::string?

Class template Medium
A. template Box<std::string> item;
B. Box<string()> item;
C. Box item<std::string>;
D. Box<std::string> item;

30 Suppose template<class T> class Base {};. Which declaration correctly defines a class template Derived<T> that publicly inherits from Base<T>?

Class template and inheritance Medium
A. template<class T> class Derived : Base<class T> {};
B. template<class T> class Derived : public Base<T> {};
C. template<class T> class Derived : public Base {};
D. class Derived<T> : public Base<T> {};

31 Which STL design feature most directly allows one algorithm such as std::find to work with several different container types?

Introduction and importance of Standard Template Library (STL) Medium
A. Containers store every element as void*
B. Algorithms operate on iterator ranges
C. Algorithms access container fields directly
D. Containers all inherit from one base class

32 A program needs unique keys maintained in sorted order with efficient key-based lookup. Which standard container best matches these requirements?

Containers Medium
A. std::multiset
B. std::set
C. std::list
D. std::vector

33 Which call correctly sorts every element of std::vector<int> values in ascending order?

Algorithms Medium
A. std::sort(values.front(), values.back());
B. std::sort(values.begin(), values.end());
C. std::sort(values.begin(), values.end() - 1);
D. std::sort(values.end(), values.begin());

34 Why must v.end() not be dereferenced for a nonempty vector v?

Iterators Medium
A. It stores the vector's current capacity value
B. It becomes valid only after calling v.back()
C. It denotes the position just after the last element
D. It denotes the final element but only for writing

35 An iterator points to an element of a vector. A later push_back causes the vector to reallocate its storage. What happens to the old iterator?

Vector container Medium
A. It is invalidated by the reallocation
B. It is converted automatically into a const iterator
C. It remains valid but points to the next element
D. It remains valid if the inserted value has the same type

36 After std::vector<int> v; v.reserve(20);, which statement is guaranteed before additional elements are inserted?

Vector container Medium
A. v.size() is 20 and all elements contain 0
B. v.size() is 0 and v.capacity() remains 0
C. v.size() is 0 and v.capacity() is at least 20
D. v.size() is 20 and v.capacity() is exactly 20

37 What is the main effect of destination.splice(destination.end(), source) for two compatible std::list<int> objects?

List container Medium
A. It merges both lists and automatically sorts the result
B. It copies all values while leaving source unchanged
C. It transfers all nodes from source to destination
D. It swaps only the final nodes of the two lists

38 Why is std::sort(items.begin(), items.end()) unsuitable when items is a std::list<int>?

List container Medium
A. std::sort cannot compare integer elements
B. std::sort requires contiguous element storage
C. std::sort requires random-access iterators
D. std::sort accepts only vector iterators

39 Function f() throws an exception, g() calls f() without a matching handler, and main() calls g() inside a matching try block. Where is the exception handled?

Exception handling mechanism Medium
A. Automatically at the end of g()
B. Nowhere because handlers cannot cross function calls
C. Automatically at the end of f()
D. In the matching handler in main()

40 Where should a catch(...) handler be placed when it follows typed handlers for the same try block?

Catching exception mechanism Medium
A. Before all typed handlers
B. Between try and the first handler
C. Inside the first typed handler
D. After all typed handlers

41 Consider the following program:

CPP
struct Guard {
    ~Guard() { throw 2; }
};

int main() {
    try {
        Guard g;
        throw 1;
    } catch (...) {
        std::cout << "caught";
    }
}



Assuming the default exception specifications generated by modern C++, what is the program's outcome?

Basics of exception handling Hard
A. It prints caught after discarding the exception thrown by the destructor.
B. It has undefined behavior because destructors cannot contain a throw expression.
C. It invokes std::terminate when the destructor throws during stack unwinding.
D. It catches the integer 2 because the destructor's exception replaces integer 1.

42 What is printed by the following program?

CPP
struct X {
    char id;
    ~X() { std::cout << id << ' '; }
};

int main() {
    try {
        X a{'A'};
        try {
            X b{'B'};
            throw 7;
        } catch (double) {
            std::cout << "D ";
        }
    } catch (int) {
        std::cout << "C";
    }
}

Exception handling mechanism Hard
A. D B A C
B. B D A C
C. B A C
D. A B C

43 What does this code print?

CPP
struct Base {
    virtual const char* name() const { return "Base"; }
    virtual ~Base() = default;
};
struct Derived : Base {
    const char* name() const override { return "Derived"; }
};

int main() {
    try {
        throw Derived{};
    } catch (Base b) {
        std::cout << b.name();
    }
}

Throwing exception mechanism Hard
A. Nothing, because a Derived object cannot match a Base handler.
B. Derived, because virtual dispatch preserves the thrown object's type.
C. Base, because the handler parameter slices the caught object.
D. The program is ill-formed because exceptions cannot be caught by value.

44 Given the handlers below, which one handles throw Derived{};?

CPP
struct Base { virtual ~Base() = default; };
struct Derived : Base {};

try {
    throw Derived{};
} catch (Base& e) {
    std::cout << "base";
} catch (Derived& e) {
    std::cout << "derived";
} catch (...) {
    std::cout << "other";
}

Catching exception mechanism Hard
A. The catch (...) handler handles it because polymorphic objects require ellipsis.
B. The Derived& handler handles it because exact matches always take priority.
C. The program is ill-formed because related exception types cannot share a try block.
D. The Base& handler handles it because handlers are tested in source order.

45 Assume Derived publicly inherits from polymorphic Base. Compare these two handlers:

CPP
void g() {
    try { throw Derived{}; }
    catch (Base& e) { throw e; }
}

void h() {
    try { throw Derived{}; }
    catch (Base& e) { throw; }
}



If each function is called inside handlers for Derived& followed by Base&, which pair is selected?

Re-throwing an exception Hard
A. g: Derived&; h: Base&
B. g: Base&; h: Base&
C. g: Derived&; h: Derived&
D. g: Base&; h: Derived&

46 Given the function template below, what happens at the marked call?

CPP
template<class T>
T combine(T a, T b) { return a + b; }

auto x = combine(1, 2.5); // marked call

Function template Hard
A. The call is ambiguous between implicit int and double instantiations.
B. Deduction fails because the two arguments imply different types for T.
C. T is deduced as int, and x becomes 3.
D. T is deduced as double, and x becomes 3.5.

47 For the forwarding-reference template below, what are the deduced types of T?

CPP
template<class T>
void inspect(T&& value);

int n = 0;
inspect(n);  // call 1
inspect(0);  // call 2

Function template Hard
A. Call 1: int; call 2: int&&
B. Call 1: const int&; call 2: int
C. Call 1: int&; call 2: int&&
D. Call 1: int&; call 2: int

48 What does the call f(p) print?

CPP
template<class T>
void f(T) { std::cout << "primary"; }

template<class T>
void f(T*) { std::cout << "pointer"; }

template<>
void f<int*>(int*) { std::cout << "special"; }

int* p = nullptr;
f(p);

Function template Hard
A. primary, because explicit specializations disable template ordering.
B. special, because an explicit specialization always wins overload resolution.
C. The call is ambiguous between the pointer overload and the specialization.
D. pointer, because overload resolution selects the pointer primary template.

49 Which replacement makes the following template well-formed?

CPP
template<class T>
struct Wrapper {
    using Container = T;

    void process() {
        /* replacement */ item{};
    }
};



The replacement must declare item using the nested type Container::value_type.

Class template Hard
A. Container::value_type item`
B. class Container::value_type item`
C. template Container::value_type item`
D. typename Container::value_type item`

50 What is printed by this class-template partial specialization?

CPP
template<class T>
struct Kind {
    static constexpr const char* name = "ordinary";
};

template<class T>
struct Kind<T*> {
    static constexpr const char* name = "pointer";
};

std::cout << Kind<const int*>::name;

Class template Hard
A. ordinary, because const int* is not exactly T*.
B. ordinary, because partial specializations ignore cv-qualified types.
C. pointer, with T deduced as const int.
D. The instantiation is ambiguous because const may qualify either level.

51 Why does return value; fail in the template below, and which replacement fixes it?

CPP
template<class T>
struct Base {
    int value = 42;
};

template<class T>
struct Derived : Base<T> {
    int get() const { return value; }
};

Class template and inheritance Hard
A. The member is static; replace it with Base<T>::value.
B. The name is ambiguous; replace it with Derived::value.
C. The member is private; replace it with Base<T>::get(value).
D. The base is dependent; replace it with this->value.

52 What mechanism causes Algorithm<Fast>::run() to call Fast::execute()?

CPP
template<class Derived>
struct Algorithm {
    void run() {
        static_cast<Derived*>(this)->execute();
    }
};

struct Fast : Algorithm<Fast> {
    void execute() { std::cout << "fast"; }
};

Class template and inheritance Hard
A. Argument-dependent lookup through the Fast class namespace
B. Runtime virtual dispatch through a generated virtual table
C. Static polymorphism through the curiously recurring template pattern
D. Function-template specialization performed when run is called

53 Which design property most directly allows one STL algorithm such as std::find to operate on arrays, vectors, and lists without those containers sharing a common base class?

Introduction and importance of Standard Template Library (STL) Hard
A. Containers are converted into a universal internal sequence before each algorithm.
B. Algorithms operate through iterator interfaces and required iterator operations.
C. Algorithms use runtime reflection to discover each container's member functions.
D. Containers inherit from a hidden standard polymorphic container abstraction.

54 An insertion into a std::unordered_map triggers a rehash but does not erase any element. Which statement correctly describes invalidation?

Containers Hard
A. All iterators are invalidated, but references and pointers to elements remain valid.
B. All references are invalidated, but iterators and pointers remain valid.
C. Only the past-the-end iterator is invalidated; element iterators remain valid.
D. All iterators, references, and pointers to stored elements are invalidated.

55 After executing the code below, which property is guaranteed?

CPP
std::vector<int> v{1, 2, 1, 3, 1};
auto new_end = std::remove(v.begin(), v.end(), 1);

Algorithms Hard
A. v.size() is 3, and [new_end, v.end()) contains only 1s.
B. v.size() is 5, and [v.begin(), new_end) equals {2, 3}.
C. v.size() is 5, and the vector's complete contents remain unchanged.
D. v.size() is 2, and the complete vector equals {2, 3}.

56 What is the logical range produced by std::unique in this example?

CPP
std::vector<int> v{1, 2, 1, 1, 2};
auto e = std::unique(v.begin(), v.end());

Algorithms Hard
A. [v.begin(), e) is {1, 2, 1}, because the final repeated value is discarded.
B. [v.begin(), e) is {1, 2}, because all duplicate values are removed.
C. [v.begin(), e) is {1, 2, 2}, because equal values become adjacent first.
D. [v.begin(), e) is {1, 2, 1, 2}, because only adjacent duplicates collapse.

57 Let v be a std::vector<int> and l a std::list<int>, each containing elements. What are the standard complexity characteristics of std::distance(v.begin(), v.end()) and std::distance(l.begin(), l.end())?

Iterators Hard
A. Both are linear time because std::distance increments every iterator.
B. Both are constant time because every container stores its size.
C. The vector distance is constant time; the list distance is linear time.
D. The vector distance is linear time; the list distance is constant time.

58 Assume sufficient memory is available. What is guaranteed by this code?

CPP
std::vector<int> v;
v.reserve(4);
v.push_back(10);
int* p = &v[0];
v.push_back(20);
std::cout << *p;

Vector container Hard
A. Dereferencing p is undefined because every push_back invalidates pointers.
B. The result is unspecified because reserve provides only a size guarantee.
C. It prints 20 because push_back may relocate the first element in place.
D. It prints 10 because the second insertion cannot exceed the reserved capacity.

59 A std::vector<int> has spare capacity, and an element is inserted into its middle without reallocation. Which iterators are invalidated?

Vector container Hard
A. Only the old past-the-end iterator is invalidated; all element iterators remain valid.
B. All iterators are invalidated even though no reallocation occurs.
C. Iterators at or after the insertion point are invalidated; earlier ones remain valid.
D. Only the iterator designating the newly inserted element is invalidated.

60 What is true after executing this code?

CPP
std::list<int> a{1, 2};
std::list<int> b{3, 4};
auto it = std::next(b.begin()); // points to 4
a.splice(std::next(a.begin()), b, it);

List container Hard
A. a is {1, 2, 4}, b is {3}, and it is invalidated by the transfer.
B. a is {1, 4, 2}, b is {3}, and it still belongs to b.
C. a is {4, 1, 2}, b is {3}, and all iterators into both lists are invalidated.
D. a is {1, 4, 2}, b is {3}, and it still refers to 4 in a.