CPA-21-02 practice question 6 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; class complex{ double re; double im; public: complex() : re(0),im(0) {} complex(double x) { re=x,im=x;}; complex(double x,double y) { re=x,im=y;} void print() { cout

Full set: 257 questions
Answer options
A: It prints: 0 0
B: It prints: 1 1
C: It prints: 2 0
D: It prints: 2 2 Correct answer
Correct Answer:
D. It prints: 2 2
Explanation

The statement c1 = i; triggers an implicit conversion because the complex class has a non-explicit constructor taking a single double argument (complex(double x)). When i (which holds the value 2.0) is assigned to c1, this converting constructor is invoked with x = 2. Inside the constructor's body, the code re=x, im=x; assigns the value of x (2) to both the re and im member variables. Therefore, calling c1.print() outputs "2 2".

Why Incorrect

A: "0 0" is the initial state from the default constructor, but this state is overwritten by the subsequent assignment. B: The value assigned from i is 2, not 1, so the member variables are set to 2. C: The single-argument constructor explicitly sets both re and im to the value of x, not just re.

References

- ISO/IEC 14882:2017 (C++17 Standard), Section 15.3.1 [class.conv.ctor], paragraph 1 (converting constructors).

- Bjarne Stroustrup, "The C++ Programming Language, 4th Edition", Section 16.2.6 (Explicit Constructors).

Scroll to Top