Exam Information
Free practice questions with explanations
C++ Institute CPA-21-02 Practice Questions
Answer a question to see the correct answer and the explanation, or click Show answer. Newest questions first.
- Questions
- 17
- Answered
- 0
- Correct
- 0
- Score
- -
-
1 Question 1 Single choice Absolute Basics
A junior developer at a logistics company compiles the following program with g++ -std=c++17 and is surprised by the output. The team must explain the behaviour in a code review before the release freeze. The program reads a single integer from standard input, then prints the result of dividing 17 by that value using integer arithmetic. The developer entered 4 and expected 4.25 to be printed. Which explanation is correct? int main() { int divisor; std::cin >> divisor; std::cout
Correct Answer: AExplanationInteger division in C++ discards the fractional part and truncates toward zero, so 17 / 4 yields 4 when both operands are int. The stream operator does not change the arithmetic type of the expression, which rules out the claim that cout promotes the result. The code compiles cleanly because reading into an int with std::cin is ordinary usage. The answer of 0 confuses truncation with rounding to a multiple of the divisor, which is not how the operator works.
-
2 Question 2 Multiple choice Accessing Data and Dealing with Exceptions
A payments team maintains a C++ service that parses transaction amounts from text. Legacy code calls std::stoi on user-supplied strings and crashes with an uncaught exception in production. The team must keep the parsing function noexcept-free and must report malformed input to callers without terminating the process. Which TWO changes meet these requirements? (Choose two.)
Correct Answer: B, DExplanationCatching std::invalid_argument and std::out_of_range around std::stoi lets the function handle both malformed text and overflow without crashing, and throwing a derived std::runtime_error gives callers a meaningful exception to handle. Replacing std::stoi with std::atoi silently turns bad input into zero, which hides errors and violates the requirement to report malformed input. Marking the function noexcept makes any escaping exception call std::terminate, which is the opposite of the required behaviour. Calling std::terminate deliberately still ends the process, so it fails the no-termination constraint.
-
3 Question 3 Order list Class Hierarchy
A game studio is refactoring a rendering engine so that Sprite and Particle both derive from a common Drawable base class, and the base class must destroy derived objects correctly when deleted through a base pointer. A junior engineer must make the changes in the correct sequence so that the code compiles and behaves safely at runtime. Arrange the steps in the correct order.
Drag the steps into the correct order, or use the arrows.
- Store Sprite and Particle objects in a std::vector of Drawable pointers.
- Delete each object through its Drawable pointer and verify that derived destructors run.
- Derive Sprite and Particle from Drawable using public inheritance.
- Declare a public virtual destructor in the Drawable base class.
Correct Answer:- Declare a public virtual destructor in the Drawable base class.
- Derive Sprite and Particle from Drawable using public inheritance.
- Store Sprite and Particle objects in a std::vector of Drawable pointers.
- Delete each object through its Drawable pointer and verify that derived destructors run.
ExplanationThe base class must declare a virtual destructor before any deletion through a base pointer can safely run derived destructors, so that step has to come before the storage and deletion steps. Derived classes must inherit publicly to be usable through Drawable pointers, which means inheritance is set up before objects are placed in the container. Storing pointers in a vector of base pointers only makes sense once the hierarchy is in place. Deleting through the base pointer is the final verification step that depends on all previous steps being complete.
-
4 Question 4 Drag and drop Flow Control and More Data Types
A firmware team writes a loop that reads 32-bit sensor flags. The code must extract the sixth bit, clear the lowest bit, and compare two values for equality only when both are true. Match each requirement to the operator that meets it. Match each requirement to the operator that meets it.
Drag each item onto its matching target. On a phone: tap an item, then tap a target.
Combine two conditions so the branch runs only if both holdClear the lowest bit of a flag wordTest whether the sixth bit of a flag word is setBitwise XORLogical ANDLogical NOTBitwise AND with 0x20Bitwise AND with the complement of 1Correct Answer:- Test whether the sixth bit of a flag word is set → Bitwise AND with 0x20
- Clear the lowest bit of a flag word → Bitwise AND with the complement of 1
- Combine two conditions so the branch runs only if both hold → Logical AND
ExplanationTesting a single bit is done with bitwise AND against a mask that has only that bit set, so 0x20 isolates the sixth bit. Clearing the lowest bit uses bitwise AND with the complement of 1, which zeroes that position while leaving the rest unchanged. Combining two boolean conditions so both must be true is the job of logical AND, which short-circuits. Bitwise XOR flips bits rather than clearing them, and logical NOT inverts a single truth value, so neither fits any requirement here.
-
5 Question 5 Dropdown Flow Control and More Data Types
A scientific computing team stores measurement counts in an unsigned 16-bit field and needs to run a loop that processes exactly the values from 10 down to 1 inclusive, stopping as soon as the counter reaches zero, without relying on unsigned wraparound. Complete the loop by selecting the correct value for each blank. for ([1] count = 10; count [2] 0; [3]) { process(count); }
Choose the correct value for each blank.
for ( count = 10; count 0; ) {
process(count);
}Correct Answer:for (unsigned short count = 10; count != 0; count--) {
process(count);
}ExplanationThe counter is declared as unsigned short to match the field width, and the loop must stop at zero, so the condition uses a not-equal test against zero rather than a relational test that would behave differently under decrement. Decrementing with count-- after each pass processes 10 through 1 and exits when the value reaches zero. Using a signed type would not preserve the stated width, and a plus-two step would skip values, so the chosen blanks are the only combination satisfying every constraint.
-
6 Question 6 Single choice Functions
A finance application has a function that adds a surcharge to an order total. The team wants callers in legacy modules to keep calling apply_surcharge(total) with one argument, while new modules specify a custom rate with apply_surcharge(total, rate). The header must avoid ambiguity and the default must be a 2 percent rate. Which declaration best meets these requirements?
Correct Answer: BExplanationA single declaration with a default argument on the trailing parameter lets legacy one-argument calls and new two-argument calls resolve to the same function, which keeps the interface unambiguous. Declaring two overloads with the same name would also work for calls but duplicates logic and is not the requested single declaration with a default. The defaulted function syntax applies only to special member functions, so the third choice is invalid. A non-const lvalue reference cannot bind to the literal 0.02, so the fourth choice does not compile.
-
7 Question 7 Multiple choice Functions
A robotics team's control library contains a function that writes status to a log buffer. Recent bugs were caused by callers passing a loop counter that the function silently modified through a reference parameter, changing the caller's variable. The team wants the function to accept large sensor structures cheaply and must prevent the modification and the copy. Which TWO parameter declarations meet these requirements? (Choose two.)
Correct Answer: A, CExplanationPassing by const reference avoids copying the structure and prevents the function from modifying the caller's object, which meets both requirements. Passing a const pointer provides the same guarantee, since the pointee cannot be modified through it, though it requires the caller to pass an address. Pass by value copies the whole structure, which violates the cost requirement. A non-const reference allows modification, the exact bug being fixed. An rvalue reference binds only to temporaries and does not prevent modification of named lvalues, so it does not meet the requirement.
-
8 Question 8 Single choice Fundamentals of the Object-Oriented Approach
A telemetry service keeps a count of active connections that must be shared across all instances of a Connection class, and the count must be initialized exactly once before any object is created. A developer places the definition of the counter inside the class body with the initializer. The build fails with an error about an in-class initializer for a non-const static member. The team has a strict rule against global variables in headers. Which fix meets the requirement?
Correct Answer: AExplanationSince C++17, a static data member can be declared inline with an initializer in the class body, which provides a single definition without a global variable and fits the team's rule. The const option would only work for integral constants and would make the value unchangeable, defeating a counter. A non-static member gives each object its own copy, which breaks the requirement of sharing one count. A namespace-scope variable in a header violates the stated rule and would cause multiple definition errors without extra care.
-
9 Question 9 Dropdown Fundamentals of the Object-Oriented Approach
A logistics system defines a Pallet class holding a weight in kilograms. Callers must be able to add two pallets with the plus operator, and the result must be a new object while both operands remain unchanged. The engineer must declare the operator as a member function and choose the correct parameter and qualifier. Complete the declaration by selecting the correct value for each blank. Pallet operator+([1] other) [2];
Choose the correct value for each blank.
Pallet operator+( other) ;Correct Answer:Pallet operator+(const Pallet& other) const;
ExplanationA binary plus operator should take its right operand by const reference so no copy is made and the argument is not modified. Marking the member function const means it does not modify the left operand, which keeps both inputs unchanged and allows calls on const objects. Passing by non-const reference would permit modification of the argument and cannot bind temporaries. The override and final qualifiers apply only to virtual functions and would not compile on a non-virtual operator here.
-
10 Question 10 Single choice More on Classes
A plugin framework defines an abstract Codec base class with a virtual encode method. A third-party module derives from Codec and mistakenly declares its method as encode(const std::string&) instead of matching the base signature exactly. The compiler accepts the class without error, but calls through Codec pointers always invoke the base implementation. The team must detect this mismatch at compile time without changing the calling code. Which change is the BEST fix?
Correct Answer: DExplanationThe override specifier asks the compiler to verify that the derived function actually overrides a virtual function in a base class, so a mismatched parameter list produces a compile error instead of silently hiding the base method. Declaring the base method final prevents overriding entirely, which is the opposite of what the plugin needs. A static member cannot be virtual, so making it static would break polymorphic dispatch. A pure virtual destructor does not address signature matching and does not force a recompile in any meaningful sense.
-
11 Question 11 Single choice More on Classes
A graphics library defines an abstract Shape class with a pure virtual area method. A developer tries to create a Shape object directly in a test and the compiler rejects the code. The developer then asks why a class with a virtual function cannot be instantiated when concrete subclasses like Circle work fine. The team wants a concise explanation to share in the design document. Which statement is correct?
Correct Answer: BExplanationA class with a pure virtual function declared with the =0 syntax is abstract and cannot be instantiated directly, while a derived class that overrides all such functions becomes concrete. Having any virtual function is not sufficient to make a class abstract, so the second statement is wrong. The presence of data members does not determine abstractness. The compiler rejects instantiation because of the pure virtual specifier, not because of a missing return type, so the fourth statement is incorrect.
-
12 Question 12 Single choice The Basics of Functions
A banking backend defines its own exception type, AccountError, derived from std::runtime_error. A function withdraw throws AccountError when funds are insufficient. A caller wraps the call in a try block with a catch clause for std::exception placed before a catch clause for AccountError. The team notices that the AccountError handler never runs in testing. What is the cause, and what is the correct fix?
Correct Answer: AExplanationHandlers are checked in the order they appear, and a catch for a base class like std::exception matches any derived exception, including AccountError through the inheritance chain. Placing the more specific AccountError handler above the general one lets it be selected first. The noexcept specifier has nothing to do with catch matching, and catch clauses do match exceptions propagating from called functions. Deriving directly from std::exception would not fix the ordering problem and would lose the runtime_error message support.
-
13 Question 13 Drag and drop The Basics of Functions
A payroll service has several exception types and must place each failure into the correct handling category so that the right recovery code runs. The team uses the standard exception hierarchy where std::logic_error and std::runtime_error are both derived from std::exception. Match each failure scenario to the standard exception class that best represents it.
Drag each item onto its matching target. On a phone: tap an item, then tap a target.
A caller passes a negative pay period count that violates a documented preconditionA database response is truncated and the parsed result is unusable at runtimeA computed index exceeds the valid range of a fixed-size containerstd::out_of_rangestd::bad_allocstd::runtime_errorstd::overflow_errorstd::invalid_argumentCorrect Answer:- A caller passes a negative pay period count that violates a documented precondition → std::invalid_argument
- A database response is truncated and the parsed result is unusable at runtime → std::runtime_error
- A computed index exceeds the valid range of a fixed-size container → std::out_of_range
ExplanationA precondition violation caught from a bad argument is represented by std::invalid_argument, which is a logic error and fits a caller passing invalid input. A truncated response that is only detected during processing is a runtime condition, so std::runtime_error is the appropriate base. An index beyond a container range matches std::out_of_range. Memory exhaustion is signalled by std::bad_alloc and is not the scenario, and overflow_error applies to arithmetic overflow rather than an unusable parse result.
-
14 Question 14 Order list Accessing Data and Dealing with Exceptions
A data-import tool must read a line from a file, convert it to an integer, and report a clear message if the file cannot be opened, without leaving the stream in an unhandled state. A developer writes the code step by step. Arrange the steps in the correct order.
Drag the steps into the correct order, or use the arrows.
- Convert the string to an integer with std::stoi inside a try block.
- Catch std::invalid_argument and report the conversion failure to the user.
- Open the file with std::ifstream and check whether the stream is in a good state.
- Read a line into a std::string using std::getline.
Correct Answer:- Open the file with std::ifstream and check whether the stream is in a good state.
- Read a line into a std::string using std::getline.
- Convert the string to an integer with std::stoi inside a try block.
- Catch std::invalid_argument and report the conversion failure to the user.
ExplanationThe stream must be opened and checked before any read, because reading from a failed stream produces no useful data. Once the file is confirmed open, a line is read into a string, which is the input the conversion needs. The conversion then runs inside a try block, since std::stoi throws on bad input. The catch handler is the last step because it only applies after the conversion has been attempted and has failed.
-
15 Question 15 Single choice Class Hierarchy
A healthcare application has a base class Device with a non-virtual destructor and a derived class Monitor that allocates an internal buffer. Code stores Monitor objects through Device pointers and deletes them. Valgrind reports that the buffer memory is never freed. The team must fix the leak with the smallest change that keeps the existing public interface. Which change is correct?
Correct Answer: AExplanationDeleting a derived object through a base pointer is undefined behaviour unless the base destructor is virtual, and making it virtual ensures the Monitor destructor runs and frees the buffer. A static destructor is not valid C++ and cannot be virtual. Making the base destructor private prevents deletion through Device pointers and would fail to compile in the existing code. Casting every pointer to Monitor is unsafe and does not fix the destruction path for objects already stored as Device pointers.
-
16 Question 16 Dropdown Class Hierarchy
A vehicle fleet system defines a Vehicle base class and a Truck subclass. Truck must inherit publicly so that code holding Vehicle references can call its methods, and it must also expose a protected member that only derived classes can reach. The engineer must write the class header with the correct inheritance keyword and access specifier. Complete the declaration by selecting the correct value for each blank. class Truck [1] Vehicle { [2]: int payload_limit; };
Choose the correct value for each blank.
class Truck Vehicle {
:
int payload_limit;
};Correct Answer:class Truck public Vehicle {
protected:
int payload_limit;
};ExplanationPublic inheritance preserves the is-a relationship so that Truck objects can be used wherever a Vehicle reference is accepted, which is the stated requirement. The protected access specifier makes payload_limit reachable from derived classes while hiding it from ordinary callers. Private inheritance would hide the base interface from Vehicle references, and public access would expose the member too broadly. The virtual and static keywords have different meanings and do not express either requirement.
-
17 Question 17 Single choice Absolute Basics
A build engineer at an embedded company is documenting how a C++ source file becomes an executable on the target toolchain. A teammate claims that the compiler performs the full job in one step and that the linker only runs when the program is first launched. The engineer must correct this in the build guide before the audit. Which statement gives the accurate sequence?
Correct Answer: AExplanationThe toolchain runs the preprocessor to handle includes and macros, then the compiler turns each translation unit into object code, and finally the linker resolves symbols across object files to produce the executable, all before the program is run. Stating that the compiler produces the executable in one step ignores the separate linking stage. The linker does not translate source, and the preprocessor does not compile to assembly. Dynamic loading at startup is a separate runtime concern and does not replace the link step.
These are 17 of the 257 questions in the full CPA-21-02 pack.
Get All 257 QuestionsGet all 257 questions & answers
Full access options for C++ Institute CPA-21-02
Self-study
PDF Version
- 257 actual exam questions
- Compatible with all devices
- Printable PDF format
- No download limits
- 90 days free updates
- 24/7 customer support
Best value
Bundle Pack
- Discounted PDF + online access
- 257 actual exam questions
- Both PDF and online practice test
- Free 90 days updates
- No download or practice limits
- 24/7 customer support
Exam simulation
Online Practice Test
- 257 actual exam questions
- Actual exam environment
- 90 days free updates
- Browser-based software
- 24/7 customer support
100% Money Back Guarantee
Your success comes first
At DumpsProvider, we give you a 100% money back guarantee on all of our exam dumps. For us, your success is the #1 priority and we are more than confident that our exam material will help you pass the CPA-21-02 Exam (CPA - C++ Certified Associate Programmer Exam) on your very first attempt.
In a rare case, if you fail your exam, we will refund your amount without asking a single question.