C++ Programming Professional Certificate — Questions and Answers
Question 1: Which stream is used to write to a file?
- ofstream (Correct answer)
- fstream
- istream
- ifstream
Correct answer: ofstream
`ofstream` (output file stream) is the class specifically designed for writing data to files in C++. You create an `ofstream` object, associate it with a file, and then use stream insertion operators (`<<`) to write data to that file.
Question 2: Which of the following correctly initializes a std::vector with five zeros?
- std::vector<int> v(5); (Correct answer)
- std::vector<int> v(5, 0, 0);
- std::vector<int> v = {5};
- std::vector<int> v[5];
Correct answer: std::vector<int> v(5);
std::vector<int> v(5) constructs a vector of 5 elements, all value-initialized to 0.
Question 3: Which operator is used to access the address of a variable?
- #
- & (Correct answer)
- @
- *
Correct answer: &
The ampersand symbol (`&`) in C++ is the address-of operator. When placed before a variable name, it returns the memory address where that variable is stored. This address can then be assigned to a pointer variable.
Question 4: Which C++20 feature allows `Point p = {.x = 1, .y = 2};` initialization syntax?
- Aggregate initialization
- Brace-enclosed initializer lists
- Structured bindings
- Designated initializers (Correct answer)
Correct answer: Designated initializers
C++20 designated initializers let you name aggregate members by their field names in initialization, matching C99's syntax.
Question 5: Which STL data structure provides LIFO (Last-In, First-Out) behavior?
- std::priority_queue
- std::queue
- std::deque
- std::stack (Correct answer)
Correct answer: std::stack
std::stack implements LIFO semantics; elements are pushed and popped from the same end (top).
Question 6: Which technique reduces dynamic dispatch overhead in C++ by resolving virtual calls at compile time?
- Runtime polymorphism with vtables
- Using std::function instead of virtual functions
- Storing objects in std::variant with std::visit
- Curiously Recurring Template Pattern (CRTP) for static polymorphism (Correct answer)
Correct answer: Curiously Recurring Template Pattern (CRTP) for static polymorphism
CRTP uses templates to implement polymorphism at compile time, so the compiler can inline derived-class methods and avoid vtable indirection entirely.
Question 7: In C++, what is the result of 5 / 2 when both operands are of type int?
- 3
- 2 (Correct answer)
- Undefined behavior
- 2.5
Correct answer: 2
Integer division truncates toward zero in C++, so 5/2 yields 2, discarding the fractional part.
Question 8: Which STL algorithm returns true only if a predicate holds for every element in a range?
- std::all_of (Correct answer)
- std::none_of
- std::find_if
- std::any_of
Correct answer: std::all_of
std::all_of returns true only if the predicate returns true for every element in the range.
Question 9: Which keyword is used to prevent a derived class from overriding a virtual function in C++11 and later?
- static
- sealed
- const
- final (Correct answer)
Correct answer: final
The 'final' specifier prevents further overriding of a virtual function in derived classes.
Question 10: What is inheritance in OOP?
- Sharing private members.
- None of the above.
- Copying all functions manually.
- Acquiring features from a base class (Correct answer)
Correct answer: Acquiring features from a base class
Inheritance is a fundamental OOP concept where a new class (derived class) acquires properties and behaviors (features) from an existing class (base class). This mechanism promotes code reusability and establishes an "is-a" relationship, allowing derived classes to extend or specialize the functionality of their base classes.
Question 11: What is a memory pool and why is it used in C++?
- A kernel-level memory allocator for OS resources
- A garbage-collected region of memory managed by the runtime
- A pre-allocated block of memory used to serve allocation requests faster than the general heap (Correct answer)
- A shared_ptr that manages multiple objects simultaneously
Correct answer: A pre-allocated block of memory used to serve allocation requests faster than the general heap
A memory pool pre-allocates a large block of memory and serves object allocations from it, reducing fragmentation and improving allocation speed.
Question 12: What is the relationship between templates & generic programming and overall C++ Programming Professional Certificate professional competency?
- It is an essential component that strengthens the overall competency framework (Correct answer)
- It is a minor supplementary skill
- It only applies to senior practitioners
- They are completely unrelated areas
Correct answer: It is an essential component that strengthens the overall competency framework
Templates & Generic Programming is an essential component of the CPP competency framework, strengthening overall professional capability and credibility.
Question 13: What is a key principle of concurrency & multithreading in C++ Programming Professional Certificate practice?
- Applying structured methodologies based on evidence and best practices (Correct answer)
- Avoiding all standardized approaches
- Relying solely on personal experience
- Minimizing documentation requirements
Correct answer: Applying structured methodologies based on evidence and best practices
Concurrency & Multithreading in C++ Programming Professional Certificate practice requires applying structured, evidence-based methodologies while adapting to specific professional contexts.
Question 14: What is the use of reinterpret_cast in pointer contexts?
- Reinterprets the raw bit pattern of a pointer as a different pointer type, with no safety guarantees (Correct answer)
- Converts a pointer to an integer and back safely across platforms
- Safely converts between related pointer types using a checked cast
- Performs a const-safe conversion between pointer types
Correct answer: Reinterprets the raw bit pattern of a pointer as a different pointer type, with no safety guarantees
reinterpret_cast reinterprets the bit pattern of a pointer as another type with virtually no safety checks, and its result is implementation-defined in most cases.
Question 15: What is the time complexity of std::binary_search on a sorted range?
- O(1)
- O(n log n)
- O(n)
- O(log n) (Correct answer)
Correct answer: O(log n)
std::binary_search operates on a sorted range and repeatedly halves the search space, achieving O(log n) time complexity.
Question 16: Which C++ standard introduced the range-based for loop?
- C++14
- C++11 (Correct answer)
- C++17
- C++03
Correct answer: C++11
The range-based for loop (for (auto x : container)) was introduced in C++11.
Question 17: In CMake, what does the `target_include_directories` command's `PUBLIC` keyword signify?
- Directories are hidden from all consumers
- Directories are added to the target and any target that links to it (Correct answer)
- Directories are only propagated to targets that link to this target
- Directories are only used when compiling the target itself
Correct answer: Directories are added to the target and any target that links to it
PUBLIC means the include directories apply both to the target itself and to any downstream targets that link against it.
Question 18: What does 'std::move' do to an object?
- Deallocates the object's memory
- Casts the object to an rvalue reference, enabling move semantics (Correct answer)
- Copies the object to a new variable
- Physically moves memory to a new location
Correct answer: Casts the object to an rvalue reference, enabling move semantics
std::move is a cast to rvalue reference; it signals that the object's resources can be transferred rather than copied.
Question 19: What does `std::optional<int> opt;` evaluate to when used in a boolean context?
- false, because it holds no value (Correct answer)
- true, because the object exists
- Undefined behavior
- Compilation error
Correct answer: false, because it holds no value
A default-constructed std::optional is disengaged, and its bool conversion returns false.
Question 20: How should CPP professionals measure success in design patterns & architecture?
- Through subjective self-assessment only
- Using defined metrics, benchmarks, and regular evaluation against established goals (Correct answer)
- By comparing only to minimum requirements
- Success measurement is not applicable
Correct answer: Using defined metrics, benchmarks, and regular evaluation against established goals
Success in design patterns & architecture is measured through defined metrics and benchmarks, with regular evaluation against established professional goals.
Question 21: What is the key difference between 'delete' and 'delete[]' in C++?
- delete is for single objects; delete[] is required to free arrays allocated with new[] (Correct answer)
- delete[] calls the destructor only once regardless of array size
- There is no difference; they are interchangeable
- delete[] is faster than delete
Correct answer: delete is for single objects; delete[] is required to free arrays allocated with new[]
Using delete on a new[]-allocated array is undefined behavior; delete[] correctly calls the destructor for every element and frees the memory.
Question 22: What does the 'this' pointer represent inside a non-static member function?
- A pointer to the class definition
- A pointer to the vtable
- A pointer to the calling object (Correct answer)
- A pointer to the base class subobject
Correct answer: A pointer to the calling object
Inside a non-static member function, 'this' is an implicit pointer to the object on which the function was called.
Question 23: Which of the following correctly declares a lambda that captures all local variables by reference?
- [=](int x){ return x; }
- [*](int x){ return x; }
- [&](int x){ return x; } (Correct answer)
- [@](int x){ return x; }
Correct answer: [&](int x){ return x; }
[&] in the capture list tells the lambda to capture all local variables from the enclosing scope by reference.
Question 24: What does the 'new' keyword return?
- A reference value.
- A memory address (Correct answer)
- An error code.
- A data value.
Correct answer: A memory address
The `new` operator in C++ is used for dynamic memory allocation on the heap. It allocates memory for an object or an array and returns a pointer, which is essentially a memory address, to the beginning of the newly allocated block of memory.
Question 25: Which smart pointer transfers ownership when assigned to another smart pointer of the same type?
- std::weak_ptr
- std::shared_ptr
- std::unique_ptr (Correct answer)
- std::auto_ptr
Correct answer: std::unique_ptr
std::unique_ptr uses move semantics, so assigning it to another unique_ptr transfers ownership and sets the source to nullptr.
Question 26: What is the role of std::weak_ptr in C++?
- To weakly enforce memory alignment for heap objects
- To observe stack-allocated objects safely
- To provide a non-owning reference that does not affect the reference count of a shared_ptr (Correct answer)
- To act as a fallback when unique_ptr ownership transfer fails
Correct answer: To provide a non-owning reference that does not affect the reference count of a shared_ptr
std::weak_ptr holds a non-owning reference to an object managed by shared_ptr without incrementing the reference count, helping break circular references.
Question 27: Which of the following correctly declares a variadic template function?
- template<typename... Args> void f(Args... args); (Correct answer)
- template<typename Args[]> void f(Args args);
- template<typename T, ...> void f(T t);
- template<variadic typename T> void f(T t);
Correct answer: template<typename... Args> void f(Args... args);
The `...` after `typename` declares a parameter pack, and `Args... args` expands it in the function parameter list.
Question 28: In C++20, what type does the three-way comparison operator (operator<=>) return?
- bool
- int
- char
- A comparison category such as std::strong_ordering (Correct answer)
Correct answer: A comparison category such as std::strong_ordering
operator<=> returns a comparison category type (std::strong_ordering, std::weak_ordering, or std::partial_ordering) that encodes less-than, equal, or greater-than.
Question 29: What is required to use STL containers like vector or map?
- #include <library>
- #include <stl>
- #include <container>
- #include <vector> (Correct answer)
Correct answer: #include <vector>
To use specific STL containers like `std::vector`, `std::map`, `std::list`, etc., you must include their respective header files. For `std::vector`, the correct header is `<vector>`, which provides the necessary class definition and associated functionalities.
Question 30: Which of the following is true about partial template specialization?
- It replaces the primary template entirely
- It requires all template parameters to be specified
- It allows specializing a template for a subset of its parameters while leaving others generic (Correct answer)
- It is supported for both function templates and class templates in C++
Correct answer: It allows specializing a template for a subset of its parameters while leaving others generic
Partial specialization lets you fix some template parameters (e.g., specialize `Pair<T, int>`) while keeping others generic; this is only allowed for class/variable templates.
Question 31: What does `if constexpr` allow in template functions (C++17)?
- Discarding branches at compile time based on a compile-time condition (Correct answer)
- Forcing the compiler to inline all branches of a conditional
- Conditionally enabling runtime exceptions in template code
- Selecting between two constexpr functions at link time
Correct answer: Discarding branches at compile time based on a compile-time condition
`if constexpr` evaluates the condition at compile time and discards the false branch entirely, preventing instantiation of ill-formed code in that branch.
Question 32: What is heap fragmentation and how does it affect C++ programs?
- It is a compiler optimization that splits large objects across memory pages
- It occurs when many small allocations and deallocations leave non-contiguous free blocks, reducing effective available memory (Correct answer)
- It occurs when the call stack overflows due to deep recursion
- It only affects programs that use garbage-collected runtimes
Correct answer: It occurs when many small allocations and deallocations leave non-contiguous free blocks, reducing effective available memory
Heap fragmentation occurs when repeated allocations and deallocations leave the heap with many small, scattered free blocks that may be unusable for larger allocations.
Question 33: Which scenario is most likely to cause a memory leak in C++?
- Allocating memory with new inside a function and returning without calling delete (Correct answer)
- Using std::vector instead of raw arrays
- Using nullptr to initialize a pointer
- Passing a pointer by reference to a function
Correct answer: Allocating memory with new inside a function and returning without calling delete
Allocating heap memory with new and not calling delete before the pointer goes out of scope causes a memory leak.
Question 34: Which of the following is a valid reason to prefer `reserve()` before filling a `std::vector`?
- It enables move semantics on the vector
- It prevents reallocations during push_back, avoiding repeated copies (Correct answer)
- It sorts elements for cache efficiency
- It initializes elements to zero
Correct answer: It prevents reallocations during push_back, avoiding repeated copies
reserve() pre-allocates capacity so subsequent push_back() calls never trigger reallocation or element copying until capacity is exceeded.
Question 35: What does `auto` as a template parameter in C++17 non-type parameters enable?
- Enabling floating-point non-type parameters in C++17
- Accepting any type including user-defined class types
- Deduction of the non-type parameter's type from the supplied value (Correct answer)
- Making the non-type parameter optional with a default
Correct answer: Deduction of the non-type parameter's type from the supplied value
C++17 allows `template<auto V>` so the type of the non-type parameter is automatically deduced from the provided constant value.
Question 36: Which modern POSIX function should be used for hostname-to-address resolution instead of the deprecated gethostbyname()?
- gethostbyname2()
- getaddrinfo() (Correct answer)
- inet_addr()
- nslookup()
Correct answer: getaddrinfo()
getaddrinfo() is the thread-safe, IPv6-capable replacement for the deprecated gethostbyname() for resolving hostnames to addresses.
Question 37: Which STL algorithm finds the minimum and maximum elements of a range simultaneously?
- std::equal_range()
- std::min_max()
- std::clamp()
- std::minmax_element() (Correct answer)
Correct answer: std::minmax_element()
std::minmax_element returns a pair of iterators pointing to the minimum and maximum elements.
Question 38: What does the 'new' keyword do in C++?
- Allocates memory on the stack.
- Allocates memory dynamically (Correct answer)
- Deletes a variable.
- Initializes a pointer to null.
Correct answer: Allocates memory dynamically
The `new` keyword in C++ is used for dynamic memory allocation. It requests memory from the heap at runtime, rather than from the stack at compile time, and returns a pointer to the newly allocated memory. This allows programs to manage memory more flexibly, especially for objects whose size or number isn't known until execution.
Question 39: Which file does vcpkg use in manifest mode to declare a project's dependencies?
- conanfile.txt
- CMakeLists.txt
- vcpkg.json (Correct answer)
- package.json
Correct answer: vcpkg.json
In vcpkg manifest mode, `vcpkg.json` in the project root lists all required packages and version constraints.
Question 40: What is a 'stub' in unit testing terminology?
- A tool that measures test execution time
- A replacement for a dependency that returns canned responses without verifying calls (Correct answer)
- A test that always passes to skip a feature
- A compiler pragma disabling warnings in test code
Correct answer: A replacement for a dependency that returns canned responses without verifying calls
A stub replaces a real dependency and provides hardcoded return values to control the system under test's behavior, without asserting how it was called.
Question 41: What is the output of this code? ```cpp std::vector<int> v = {1, 2, 3}; v.erase(v.begin() + 1); std::cout << v[1]; ```
- 3 (Correct answer)
- 2
- 1
- Undefined behavior
Correct answer: 3
Erasing index 1 (value 2) shifts the remaining elements left, so v[1] becomes 3.
Question 42: What does the placement new operator do in C++?
- Allocates aligned memory automatically
- Replaces an existing object in place without reallocation
- Allocates memory on the heap only
- Constructs an object at a pre-allocated memory address (Correct answer)
Correct answer: Constructs an object at a pre-allocated memory address
Placement new constructs an object at a specific, pre-allocated memory location without performing any additional allocation.
Question 43: What does the '*' operator do when used with pointers?
- Returns the value stored at the memory address (Correct answer)
- Returns the address.
- Creates a new address.
- Returns the pointer name.
Correct answer: Returns the value stored at the memory address
When the asterisk symbol (`*`) is used with a pointer variable, it acts as the dereference operator. It retrieves the value that is stored at the memory address currently held by the pointer, effectively "accessing" the data the pointer points to.
Question 44: What does the 'explicit' keyword do when applied to a constructor?
- Prevents the constructor from being used for implicit type conversions (Correct answer)
- Makes the constructor virtual
- Makes the constructor inline
- Forces the constructor to initialize all members
Correct answer: Prevents the constructor from being used for implicit type conversions
The explicit keyword prevents the compiler from using that constructor for implicit single-argument conversions.
Question 45: Which template feature allows a single template to handle both lvalue and rvalue references universally?
- Pointer templates with T*
- Rvalue-only overloads with T&&
- Const references with const T&
- Forwarding references (universal references) with T&& (Correct answer)
Correct answer: Forwarding references (universal references) with T&&
When `T&&` appears in a deduced context, it becomes a forwarding (universal) reference that binds to both lvalues and rvalues.
Question 46: What is the result of this expression in C++? ```cpp std::cout << (true + true + false); ```
- true
- 2 (Correct answer)
- 1
- Compilation error
Correct answer: 2
In arithmetic context, true converts to 1 and false to 0, so 1+1+0 = 2.
Question 47: What problem does `std::declval<T>()` solve in template metaprogramming?
- It declares a new variable of type T at compile time
- It deduces the value category of an expression involving T
- It converts T to its decayed type for use in decltype
- It creates a reference to T in unevaluated contexts without requiring a constructor (Correct answer)
Correct answer: It creates a reference to T in unevaluated contexts without requiring a constructor
`std::declval<T>()` produces a value of type T in unevaluated contexts (like `decltype`), enabling type queries on non-constructible types.
Question 48: What is the output of: int x = 5; int& ref = x; ref = 10; std::cout << x;
- 5
- Compilation error
- Undefined behavior
- 10 (Correct answer)
Correct answer: 10
ref is a reference to x, so assigning 10 to ref modifies x directly, and outputting x yields 10.
Question 49: Which stream is used to read from a file?
- ifstream (Correct answer)
- istream
- fstreamwrite
- ofstream
Correct answer: ifstream
`ifstream` (input file stream) is the class specifically designed for reading data from files in C++. You create an `ifstream` object, associate it with a file, and then use stream extraction operators (`>>`) or `getline()` to read data from that file.
Question 50: Which file open mode flag creates a new file and truncates it if it already exists?
- std::ios::app
- std::ios::in
- std::ios::trunc (Correct answer)
- std::ios::ate
Correct answer: std::ios::trunc
std::ios::trunc discards any existing content when the file is opened.
Question 51: What is a std::pair<int, std::string> most analogous to?
- A struct with two fields 'first' and 'second' of the specified types (Correct answer)
- A two-element array of mixed types
- A map entry with integer keys
- A struct with exactly two named members of fixed types
Correct answer: A struct with two fields 'first' and 'second' of the specified types
std::pair holds exactly two values accessible as .first and .second of the types specified in the template arguments.
Question 52: Which of the following best describes 'dependency injection' as applied to improve C++ unit testability?
- Passing dependencies (e.g., interfaces or pointers) into a class rather than constructing them internally, so tests can supply mocks (Correct answer)
- Using #include to pull in test helper headers
- Linking test binaries with production libraries at runtime
- Using constexpr to evaluate logic at compile time
Correct answer: Passing dependencies (e.g., interfaces or pointers) into a class rather than constructing them internally, so tests can supply mocks
Dependency injection decouples a class from its concrete dependencies, making it straightforward to inject mock objects during testing instead of real implementations.
Question 53: What does std::copy_if() do compared to std::copy()?
- Copies in reverse order
- Only copies elements satisfying a predicate (Correct answer)
- Copies to a sorted destination
- Copies unique elements only
Correct answer: Only copies elements satisfying a predicate
std::copy_if applies a predicate and copies only elements for which it returns true.
Question 54: What is the difference between shallow copy and deep copy in the context of pointers?
- Shallow copy copies pointer values; deep copy allocates new memory and copies the pointed-to data (Correct answer)
- There is no difference if raw pointers are not used
- Shallow copy is performed by move constructors; deep copy by copy constructors
- Shallow copy uses memcpy; deep copy uses std::copy
Correct answer: Shallow copy copies pointer values; deep copy allocates new memory and copies the pointed-to data
A shallow copy copies the pointer address (both copies point to the same data), while a deep copy allocates new memory and duplicates the pointed-to data.
Question 55: What is the output of: int arr[3] = {10,20,30}; int* p = arr; std::cout << *(p+2);
- 10
- 30 (Correct answer)
- 20
- Undefined behavior
Correct answer: 30
p+2 advances the pointer by 2 integer positions, pointing to the third element (30), and dereferencing it yields 30.
Question 56: What does the `-O2` flag passed to g++ primarily enable?
- A standard set of optimizations that do not involve speed-space tradeoffs (Correct answer)
- Link-time optimization
- Debug symbol generation
- Profile-guided optimization
Correct answer: A standard set of optimizations that do not involve speed-space tradeoffs
-O2 enables most speed optimizations that don't significantly increase code size, such as inlining, loop optimizations, and common subexpression elimination.
Question 57: What is a memory leak?
- Allocated memory not freed (Correct answer)
- Too many variables.
- Pointer reinitialization.
- Stack overflow.
Correct answer: Allocated memory not freed
A memory leak occurs when a program allocates memory dynamically (e.g., using `new`) but fails to deallocate it (e.g., using `delete`) when it's no longer needed. This leads to a gradual consumption of available memory, potentially causing the program or system to run out of memory over time.
Question 58: What is the result of calling std::abort() compared to throwing an unhandled exception?
- They are identical in behavior
- std::abort() only works inside catch blocks
- std::abort() terminates immediately without stack unwinding; an unhandled exception calls std::terminate() (Correct answer)
- Both call destructors before terminating
Correct answer: std::abort() terminates immediately without stack unwinding; an unhandled exception calls std::terminate()
std::abort() terminates immediately without calling destructors or atexit handlers; an unhandled exception calls std::terminate() which by default calls abort().
Question 59: Which symbol is used to terminate a statement in C++?
- :
- ; (Correct answer)
- .
- ,
Correct answer: ;
In C++, the semicolon (;) acts as a statement terminator, signaling the end of a complete instruction or declaration to the compiler. Without it, the compiler would not know where one statement ends and the next begins, leading to syntax errors. This is a fundamental rule for structuring C++ code.
Question 60: What happens when you delete a pointer that was not allocated with new?
- It is undefined behavior (Correct answer)
- The memory is returned to the OS safely
- The program silently ignores the delete
- A std::bad_alloc exception is thrown
Correct answer: It is undefined behavior
Deleting a pointer that wasn't allocated with new is undefined behavior and can corrupt the heap or crash the program.
Question 61: What is the effect of using delete on a pointer twice (double free)?
- A std::logic_error exception is thrown
- The memory is freed and then reclaimed by a fallback allocator
- The second delete is silently ignored
- Undefined behavior, often causing heap corruption or a crash (Correct answer)
Correct answer: Undefined behavior, often causing heap corruption or a crash
Calling delete twice on the same pointer is undefined behavior and typically causes heap corruption or a program crash.
Question 62: What is the purpose of the `-fsanitize=undefined` compiler flag in GCC/Clang?
- Enables profile-guided optimization
- Activates thread safety analysis
- Instruments the binary to trap undefined behavior at runtime (UBSan) (Correct answer)
- Enables memory leak detection
Correct answer: Instruments the binary to trap undefined behavior at runtime (UBSan)
The UndefinedBehaviorSanitizer (UBSan) flag instruments the program to abort or report signed integer overflow, null dereference, and other C++ undefined behavior at runtime.
Question 63: What is a 'dangling pointer' in C++?
- A pointer that points to nullptr
- A pointer that points to memory that has been freed or gone out of scope (Correct answer)
- A pointer to a constant value
- A pointer declared but never initialized
Correct answer: A pointer that points to memory that has been freed or gone out of scope
A dangling pointer points to memory that is no longer valid, such as after delete or when a local variable's scope ends.
Question 64: Which STL container provides O(1) average-case insertion, deletion, and lookup?
- std::map
- std::set
- std::unordered_map (Correct answer)
- std::multimap
Correct answer: std::unordered_map
std::unordered_map uses a hash table internally, giving O(1) average-case for these operations.
Question 65: Which of the following is an advantage of using std::list over std::vector?
- O(1) insertion and deletion anywhere in the list given an iterator (Correct answer)
- Better cache locality
- Faster random access by index
- Lower memory overhead per element
Correct answer: O(1) insertion and deletion anywhere in the list given an iterator
std::list (doubly-linked list) allows O(1) insertion/deletion at any position given an iterator, whereas std::vector requires O(n) shifting.
Question 66: What is the difference between stack and heap memory in C++?
- Stack memory is automatically managed and limited in size; heap memory is manually managed and larger (Correct answer)
- Stack memory stores global variables; heap stores local variables
- Stack memory is slower to access than heap memory
- Stack memory is manually managed; heap memory is automatic
Correct answer: Stack memory is automatically managed and limited in size; heap memory is manually managed and larger
Stack memory is automatically managed by the compiler with a limited size, while heap memory is manually allocated/deallocated and can be much larger.
Question 67: What is the output of the following code? ```cpp int x = 5; std::cout << x++ << " " << ++x; ```
- 5 6
- 6 7
- 6 6
- 5 7 (Correct answer)
Correct answer: 5 7
x++ returns 5 (post-increment), then ++x increments to 7 and returns 7, giving '5 7'.
Question 68: In C++, what is 'object slicing'?
- Losing derived class data when assigning a derived object to a base class by value (Correct answer)
- Dividing a large struct into smaller structs
- Splitting an object across multiple memory pages
- Extracting a subset of an array
Correct answer: Losing derived class data when assigning a derived object to a base class by value
Object slicing occurs when a derived class object is assigned/copied to a base class variable by value, discarding the derived portion.
Question 69: What problem does `std::scoped_lock` (C++17) solve compared to calling `std::mutex::lock()` on multiple mutexes in sequence?
- It avoids priority inversion by temporarily boosting thread priority
- It allows the same mutex to be locked twice by the same thread
- It prevents deadlock by acquiring all mutexes atomically using a deadlock-avoidance algorithm (Correct answer)
- It reduces lock contention by using spin-locking instead of blocking
Correct answer: It prevents deadlock by acquiring all mutexes atomically using a deadlock-avoidance algorithm
`std::scoped_lock` acquires multiple mutexes using a deadlock-avoidance algorithm (equivalent to `std::lock`), preventing the classic lock-ordering deadlock when two threads acquire the same two mutexes in opposite order.
Question 70: What is the result of dereferencing a nullptr in C++?
- Returns 0
- Undefined behavior, typically a segmentation fault (Correct answer)
- Returns an uninitialized value
- Throws a std::null_ptr_exception
Correct answer: Undefined behavior, typically a segmentation fault
Dereferencing nullptr is undefined behavior, commonly manifesting as a segmentation fault or access violation at runtime.
Question 71: Which pattern is best suited for implementing undo/redo functionality in an application?
- Memento
- Command (Correct answer)
- State
- Observer
Correct answer: Command
The Command pattern encapsulates operations as objects with execute/undo methods, making undo/redo straightforward.
C++ Programming Professional Certificate
This certificate validates a candidate's expertise in C++ programming, covering fundamental concepts, object-oriented programming, and advanced features.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds