Limited-Time Offer: Enjoy 50% Savings! Coupon code: 50OFF Use it at checkout
Skip to content

Free C++ Institute CPA - C++ Certified Associate Programmer Exam CPA-21-02 Exam Questions

Last updated: · 11 practice questions with answers and explanations

Page: 1 / 18 Total 257 questions

Want more questions? Get Premium Access.

Question 1

New Single answer

Topic: Absolute Basics

Skill tested: Distinguishes source-code compilation from linking and executable generation.

A small engineering team distributes a command-line utility written in C++ to users who do not have a compiler installed. The team has one source file, `tool.cpp`, and uses a conventional hosted C++ toolchain. A new developer claims that producing an object file is sufficient for users to run the utility. Which build step must the team perform after compiling the source so that it can provide a runnable program, assuming compilation succeeds?

Correct Answer: C. Link the compiled object code with required library code to produce an executable.
Explanation:

Compilation translates the C++ source into object code, but an object file commonly contains unresolved references and is not by itself the finished program. The linker combines object code and required library code, resolving references to create an executable suitable for the target environment. A compiler does not generally produce a high-level program for the operating system to interpret, and changing a filename extension does not transform source or object code into an executable. Distributing a compiler to users is unnecessary when the program has been built for their platform.

Question 2

New Single answer

Topic: Flow Control and More Data Types

Skill tested: Applies short-circuit logical evaluation to avoid unsafe operand evaluation.

A telemetry reader obtains a signed integer `count` from an external source. Its storage buffer has capacity for 64 entries, and the program must inspect `buffer[count - 1]` only when `count` is positive and no greater than the capacity. The expression is used in an `if` condition, and the team wants a single condition that safely rejects zero, negative, and oversized values before indexing. Which expression has the required behavior in C++?

Correct Answer: D. `count > 0 && count
Explanation:

Built-in `&&` evaluates operands from left to right and stops as soon as an operand is false. Thus, the buffer access occurs only after both the positive-count and upper-bound checks succeed, making `count - 1` a valid index from 0 through 63. Bitwise `&` does not provide the required short-circuit protection. The disjunction accepts values that should be rejected, while placing the access before the upper-bound check can access outside the buffer for an oversized count.

Question 3

New Multiple answers

Topic: Functions

Skill tested: Selects parameter-passing mechanisms that preserve caller state or avoid unnecessary copying.

A geometry library exposes a large `Polygon` type and a small `Point` type. A function must calculate a perimeter from a polygon without modifying it. Another function must translate a point in place so the caller observes the updated coordinates. The library uses ordinary function parameters and should avoid copying the polygon. Which two declarations best express these requirements? Select TWO.

Correct Answer: A. `double perimeter(const Polygon& polygon);`; E. `void translate(Point& point, double dx, double dy);`
Explanation:

A `const Polygon&` parameter lets `perimeter` read the existing polygon without copying it and prevents modification through that parameter. A non-const `Point&` lets `translate` update the caller's object directly. Passing the polygon by value can copy a large object, contrary to the stated goal. A const reference cannot support in-place updates, and passing a point by value changes only the local copy, so the caller would not see the translation.

Question 4

New Single answer

Topic: Accessing Data and Dealing with Exceptions

Skill tested: Uses string conversion and exception handling for invalid numeric input.

A configuration tool reads a port number as a `std::string` and then converts it to an integer before validating the permitted range, 1 through 65535. The conversion may fail if the string contains no valid integer representation, and the tool must report that failure rather than terminate unexpectedly. Which approach correctly handles the conversion failure?

Correct Answer: C. Use `std::stoi(text)` inside a `try` block and catch `std::invalid_argument` and `std::out_of_range`.
Explanation:

`std::stoi` converts a string to an integer and can throw `std::invalid_argument` when no conversion can be performed or `std::out_of_range` when the result cannot be represented as an `int`. Catching these exceptions allows the tool to report malformed or unrepresentable input. A string is not implicitly parsed by assignment, and its length is unrelated to its numeric value. Catching by value can slice exception objects, and continuing to use a result after conversion has thrown is not valid; range validation should follow successful conversion.

Question 5

New Single answer

Topic: Fundamentals of the Object-Oriented Approach

Skill tested: Distinguishes class-wide static state from per-object instance state.

A monitoring application creates many `Sensor` objects. Each sensor stores its own current reading, while the application must maintain one count of how many sensors have been created. The count should be shared by every `Sensor` object rather than duplicated in each object, and callers should be able to query it through the class name. Which design meets these requirements?

Correct Answer: A. Keep `reading` as an ordinary data member, declare `createdCount` as `static`, and provide a static accessor.
Explanation:

An ordinary data member belongs to each object, so `reading` can vary independently for every sensor. A static data member belongs to the class and represents shared state; a static accessor can expose that count through the class without requiring a particular object. Making both members static would incorrectly share sensor readings. Keeping the count non-static would create a separate count in each object and would not provide the single class-wide value the application requires.

Question 6

New Multiple answers

Topic: Class Hierarchy

Skill tested: Applies public inheritance access rules to inherited member accessibility.

A library defines `Device` with a public operation `start()`, a protected calibration value, and a private serial-number field. `SpecialDevice` derives publicly from `Device`. A client must be able to call `start()` on a `SpecialDevice`, and the derived implementation must be able to use the calibration value. The serial number must remain inaccessible to both ordinary clients and the derived class. Which two statements correctly describe this design? Select TWO.

Correct Answer: B. Public inheritance keeps the base public operation public and its protected member protected in the derived class.; C. The derived implementation can use the protected calibration value, but ordinary clients cannot access it through a `SpecialDevice` object.
Explanation:

With public inheritance, the base class's public and protected access levels remain public and protected, respectively, in the derived class. Therefore clients can call `start()`, while `SpecialDevice` member functions can use the protected calibration value. Private base members are not directly accessible to derived-class code, regardless of inheritance access. Private inheritance would make inherited public members private within the derived class's public interface, so clients could not call `start()` through a `SpecialDevice` object.

Question 7

New Single answer

Topic: More on Classes

Skill tested: Uses virtual functions and base references to achieve runtime polymorphism.

A rendering framework stores several shapes in a collection of `Shape` pointers. Each derived shape provides its own `draw` implementation. During rendering, the framework calls `draw` through each base-class pointer, but testing shows that the base implementation is always selected. The team must preserve the shared collection interface and dispatch to the object-specific implementation at runtime. Which change is most appropriate?

Correct Answer: C. Declare `Shape::draw` as a virtual member function and override it in each derived shape.
Explanation:

Runtime polymorphism through a base pointer requires a virtual function. Declaring `Shape::draw` virtual enables dynamic dispatch, so a call through a `Shape` pointer invokes the final overrider for the object's dynamic type. Derived declarations should match the base signature and can use `override` to catch mismatches. Overloading creates different compile-time signatures rather than runtime dispatch; static functions are not dynamically dispatched, and friendship affects access rather than method selection.

Question 8

New Multiple answers

Topic: The Basics of Functions

Skill tested: Selects exception handlers using catch-type matching and derived-to-base exception relationships.

A file-processing routine may throw either `std::out_of_range` when a parsed value exceeds its permitted range or `std::runtime_error` when the file cannot be read. The caller wants a specific message for range errors and a separate message for other runtime errors. It must not accidentally handle a range error with the general runtime-error handler first. Which two handler arrangements meet the requirement? Select TWO.

Correct Answer: B. Catch `const std::out_of_range&` first, then catch `const std::runtime_error&`.; E. Catch `const std::out_of_range&` first, then catch `const std::exception&`.
Explanation:

`std::out_of_range` derives from `std::runtime_error`, which derives from `std::exception`. Handlers are considered in source order, so the more specific range handler must precede a handler for either base type. Arrangement A then catches other runtime errors in the second handler; arrangement D catches them in the `std::exception` handler. Putting a base-type handler first would consume derived exceptions before the specific handler can run. Catching by const reference avoids unnecessary copying and possible slicing.

Question 9

New Single answer

Topic: Absolute Basics

Skill tested: Uses formatted stream extraction and checks stream state after input.

A batch program reads a sequence of integer measurements from standard input, one value at a time, until the input ends. Some input files may contain a malformed token, and the program must not use an uninitialized or stale measurement after extraction fails. Which loop structure correctly processes only successfully extracted integers?

Correct Answer: A. `int value; while (std::cin >> value) { process(value); }`
Explanation:

Stream extraction returns the stream, whose state can be tested in a condition. In `while (std::cin >> value)`, the body runs only when extraction succeeds, so malformed input and end-of-file both stop processing before an invalid value is used. Checking `eof()` before attempting extraction is insufficient because EOF is generally set by a failed read, which can result in processing an invalid value. The other loops similarly process before confirming that the current extraction succeeded, or incorrectly treat zero as a terminator.

Question 10

New Single answer

Topic: Functions

Skill tested: Resolves overloaded functions using argument types and standard conversion ranking.

A numeric utility offers these overloads: `void record(int);` and `void record(double);`. A call site receives a value declared as `float` and invokes `record(value)`. The team wants to know which overload the compiler selects under ordinary overload resolution, without adding casts or further overloads. Which statement is correct?

Correct Answer: B. The `double` overload is selected because conversion from `float` to `double` is a promotion, while conversion to `int` is a conversion.
Explanation:

In overload resolution, a floating-point promotion from `float` to `double` is a better conversion sequence than a floating-integral conversion from `float` to `int`. Therefore `record(double)` is selected. Both overloads are viable, but the presence of two possible conversions does not by itself make a call ambiguous; their rankings matter. The conversion does not require an explicit cast, and the `int` overload is not preferred merely because it accepts a numeric value.

Question 11

New Single answer

Topic: Accessing Data and Dealing with Exceptions

Skill tested: Applies namespace qualification to resolve names without importing an entire namespace.

A codebase uses both `std::string` and a project-defined `config::string` type. In one function, the developer writes `using namespace std;` to avoid qualifying standard-library names, but this makes an unqualified `string` unclear and may create further name conflicts as the project grows. The team wants a local, explicit fix without changing either type's name or importing all of `std`. What should the developer do?

Correct Answer: D. Use `std::string` and `config::string` explicitly at the points where each type is needed.
Explanation:

Namespace qualification makes the intended type unambiguous: `std::string` names the standard-library string class, while `config::string` names the project type. This local and explicit approach avoids importing unrelated names into the scope and reduces collision risk. A `using` declaration cannot rename an existing standard type to `std::text`; bringing both namespaces into the same scope does not create a reliable rule for choosing between conflicting names. Local variables also cannot resolve a type-name ambiguity in the proposed way.