CPA-21-02 Cpa – C++ Certified Associate Programmer Practice Questions
Prepare for CPA-21-02 with more than an answer.
- Exam fee
- $345 USD
- Level
- Associate
- Valid for
- lifetime
Domains covered on the exam 5
- Types & Operators24.5%
- Control & Exceptions18%
- Functions & Preprocessor Directives17.5%
- Pointers11%
- Classes & Namespaces29%
- 1
A developer is creating a template function
processDatathat should behave differently forinttypes than for all other types. Which C++ feature allows for creating a specialized implementation of a template for a specific type? (Select the best answer)Show answer details
Correct answer: C
Template specialization is the C++ mechanism for providing a custom implementation of a function template, class template, or member template for a specific data type. The syntax for specializing the
processDatafunction forintwould be:template void processData (int data) { ... }This allows the compiler to select this specific version when
processDatais called with anint, while using the generic template for all other types. - 2
A developer is trying to implement a copy constructor for the
Widgetclass. Which of the following signatures is the correct and canonical form for a copy constructor?class Widget { private: int* data; public: // ... other members // Correct copy constructor signature? };Show answer details
Correct answer: B
The canonical signature for a copy constructor is
ClassName(const ClassName& other). It must take its parameter by reference to avoid infinite recursion (passing by value would require a copy). The parameter should be aconstreference because the copy operation should not modify the source object. - 3
What is the output of the following program?
#include class Base { public: virtual void print() { std::cout << "Base "; } }; class Derived : public Base { public: void print() override { std::cout << "Derived "; } }; void display(Base b) { b.print(); } int main() { Derived d; display(d); return 0; }Show answer details
Correct answer: B
The function
displaytakes its parameterbby value. When theDerivedobjectdis passed todisplay, a copy is made. Because the parameter type isBase, theDerivedpart of the object is "sliced off", and only theBasepart is copied intob. Insidedisplay,bis aBaseobject, not aDerivedobject. Therefore, the callb.print()invokesBase::print(), notDerived::print(). Polymorphism only works with pointers or references. - 4
The
throw()exception specifier, while part of older C++ standards, is deprecated in C++11 and removed in C++17. What is its modern C++ equivalent, used to specify that a function will not throw any exceptions?Show answer details
Correct answer: C
In C++11 and later, the
noexceptspecifier should be used to indicate that a function does not throw exceptions. It provides stronger compile-time guarantees and enables more optimizations than the deprecatedthrow()specifier. For example:void myFunction() noexcept; - 5
What is the primary mechanism in C++ to resolve the ambiguity and state duplication caused by the 'diamond problem' in multiple inheritance?
graph TD A[Base] --> B[Derived1] A --> C[Derived2] B --> D[FinalDerived] C --> DShow answer details
Correct answer: B
Virtual inheritance is the C++ feature designed specifically to solve the diamond problem. By having
Derived1andDerived2inheritvirtual-ly fromBase, it ensures that any class inheriting from bothDerived1andDerived2(likeFinalDerived) will contain only one instance of theBaseclass subobject. This resolves ambiguity when accessing members ofBasefrom an object ofFinalDerived. - 6
A software engineer is developing a custom memory pool for an embedded system with tight memory constraints. The goal is to avoid standard library overhead. The following code snippet is part of the memory manager. What is the primary issue with this implementation?
Show answer details
Correct answer: B
The core issue is memory alignment.
new char[POOL_SIZE]returns a pointer that is guaranteed to be aligned forchar, but not necessarily for any arbitrary typeT. IfThas stricter alignment requirements (e.g.,doubleor a struct with specific members), placing it at an unaligned addresspool + offsetinvokes undefined behavior. A robust memory pool must account foralignof(T)when calculating offsets. - 7
A developer is building a high-performance logging framework. To avoid ambiguity and ensure type safety, they want to prevent implicit conversions from integers to their custom
LogLevelenum class. Which code snippet correctly achieves this?Show answer details
Correct answer: C
The
enum class(scoped enumeration) is specifically designed to provide strong type safety. It prevents implicit conversions to and from integer types. Programmers must explicitly cast if a conversion is needed. The callsetLogLevel(0)will fail to compile because0is anintand cannot be implicitly converted to theLogLeveltype. - 8
A junior developer wrote the following function to process a configuration file. During a code review, a senior developer points out a potential issue with exception safety. What is the primary problem?
#include #include #include void processConfig(const char* filename) { std::ifstream* file = new std::ifstream(filename); if (!file->is_open()) { delete file; throw std::runtime_error("Cannot open file"); } // Assume this function can throw an exception parseData(*file); delete file; }Show answer details
Correct answer: B
This code violates the RAII (Resource Acquisition Is Initialization) principle. If
parseData(*file)throws an exception, the function's execution stack is unwound, and control transfers to the nearestcatchblock. The finaldelete file;line is skipped, resulting in a memory leak. The correct approach is to manage the resource with an object whose destructor handles cleanup, such as creating thestd::ifstreamobject on the stack or using a smart pointer likestd::unique_ptr. - 9
An architect is designing a system with different types of user accounts (e.g.,
AdminUser,GuestUser,PowerUser), all derived from a commonUserbase class. The system needs a factory function that can create any type of user account based on a string identifier and return a pointer to the baseUserclass. However, the architect wants to prevent clients from accidentally slicing the objects if they are copied. Which of the following are necessary steps to achieve this design? (Select TWO)Show answer details
Correct answer: A, C
- 10
Consider the following macro definition. What is the output when the
mainfunction is executed?#include #define SQUARE(x) x * x int main() { int a = 4; std::cout << SQUARE(a + 1); return 0; }Show answer details
Correct answer: B
The preprocessor performs a direct text substitution. The line
std::cout << SQUARE(a + 1);expands tostd::cout << a + 1 * a + 1;. Due to operator precedence, the multiplication1 * ais performed first. The expression evaluates as4 + (1 * 4) + 1, which is4 + 4 + 1, resulting in9. To fix this, the macro should be defined with parentheses:#define SQUARE(x) ((x) * (x)).
