CPA-21-02 practice question 30 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; class A { public: void Print(){ cout

Full set: 257 questions
Answer options
A: It prints: BBB
B: It prints: AAA Correct answer
C: It prints: ABC
D: It prints: ABB
Correct Answer:
B. It prints: AAA
Explanation

In C++, function calls are resolved based on the static type of the pointer unless the function is declared as virtual in the base class. Here, obj is a pointer of type A. The Print() function in class A is not declared as virtual. Therefore, static binding (early binding) occurs, and the compiler resolves the call to A::Print() for all three assignments, regardless of whether obj points to an object of type A, B, or C. The output is "A" printed three times.

Why Incorrect

A. Incorrect because A::Print() is not virtual, so dynamic dispatch to B or C does not occur.
C. Incorrect because polymorphism requires the base class function to be virtual.
D. Incorrect because static binding applies to all calls, invoking A::Print() every time.

References

1. ISO/IEC 14882:2017, Programming Languages — C++, Section 13.3 [class.virtual], Paragraph 2 (Virtual functions and dynamic binding).

2. ISO/IEC 14882:2017, Programming Languages — C++, Section 8.2.2 [expr.call], Paragraph 1 (Function call resolution).

3. Stroustrup, B. (2013). The C++ Programming Language (4th ed.). Addison-Wesley Professional. Chapter 20.3.2 (Virtual Functions).

Scroll to Top