This question is based on the following C++ code segment and class FUN: class…
2022
This question is based on the following C++ code segment and class FUN: class FUN { int CODE; public: FUN(); // Function1 FUN(int C); // Function2 FUN(FUN &F); // Function3 void DISP(); // Function4 ~FUN(); // Function5 }; void main() { FUN F1; ________ // BLANK
- A.
FUN F2;
- B.
FUN F2(501);
- C.
FUN F2(F1);
- D.
FUN F2 = F1;
Attempted by 146 students.
Show answer & explanation
Correct answer: C
Answer: Both FUN F2(F1); and FUN F2 = F1; invoke the copy constructor FUN(FUN &F).
FUN F2(F1); — direct initialization: constructs F2 by calling the copy constructor with F1.
FUN F2 = F1; — copy initialization: also calls the copy constructor to create F2 (this is not assignment).
Why the other statements do not invoke the copy constructor:
FUN F2; — calls the default constructor FUN(), it does not use the existing object F1.
FUN F2(501); — calls the parameterized constructor FUN(int C) with the integer 501, not the copy constructor.
Note: The copy constructor is declared as FUN(FUN &F) (a non-const reference). Both direct initialization and copy initialization can bind the existing object F1 to that parameter and so will invoke the copy constructor.