C++ (copy construction and copy initialization) — do all three objects hold the same value and print identically?\n\n#include<iostream.h>\nclass CuriousTab {\n int x;\npublic:\n CuriousTab() { x = 0; }\n CuriousTab(int xx) { x = xx; }\n CuriousTab(CuriousTab &objB) { x = objB.x; }\n void Display() { cout << x << " "; }\n};\nint main(){\n CuriousTab objA(25);\n CuriousTab objB(objA); // copy constructor\n CuriousTab objC = objA; // copy initialization → copy constructor\n objA.Display(); objB.Display(); objC.Display();\n return 0;\n}\n\nChoose the correct statement.

Difficulty: Easy

Correct Answer: The program will print the output 25 25 25 .

Explanation:


Introduction / Context:
This program contrasts direct construction from an int with copy construction from an existing object, and shows that copy initialization uses the copy constructor too. It asks whether all three objects end up with the same observable state.


Given Data / Assumptions:

  • objA is initialized with 25.
  • objB(objA) invokes the copy constructor.
  • objC = objA uses copy initialization, which also calls the copy constructor.
  • Display() prints x followed by a space.


Concept / Approach:
The user-defined copy constructor assigns x = objB.x (source’s x). Therefore objects constructed from objA will copy 25 into their own x. No undefined behavior occurs and all objects are well-initialized.


Step-by-Step Solution:

1) objA.x = 25 via CuriousTab(int).2) objB.x = objA.x = 25 via copy ctor.3) objC.x = objA.x = 25 via copy initialization (copy ctor).4) Printing in order yields "25 25 25 ".


Verification / Alternative check:
Modify objA after constructing objB/objC; prints remain the old values because copies are by value, not references.


Why Other Options Are Wrong:

  • Garbage values would require uninitialized members, which is not the case.
  • Compile error does not occur; all methods are defined.


Common Pitfalls:
Believing that copy initialization differs semantically from explicit copy construction in selecting the copy constructor.


Final Answer:
The program will print the output 25 25 25 .

More Questions from Constructors and Destructors

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion