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 questionsThe 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".
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.
- 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).
Keep practicing
Take the free CPA-21-02 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other CPA-21-02 practice questions
- Question 1What happens when you attempt to compile and run the following code? #include using names…
- Question 2What happens when you attempt to compile and run the following code? #include #include us…
- Question 3Which of the following statements are correct about an array? int tab[10];
- Question 4What happens when you attempt to compile and run the following code? #include #include us…
- Question 5What is the output of the program if characters 'h', 'e', 'l', 'l' , 'o' and enter are su…
- Question 7What happens when you attempt to compile and run the following code? #include using names…
