C++ pointer-based “copy constructor” overload: what will this program print when constructing from a heap object pointer?\n\n#include<iostream.h>\nclass CuriousTab{\n int x, y;\npublic:\n CuriousTab(){ x = 0; y = 0; }\n CuriousTab(int xx, int yy){ x = xx; y = yy; }\n CuriousTab(CuriousTab objB){ x = objB->x; y = objB->y; } // nonstandard pointer-taking ctor\n void Display(){ cout << x << " " << y; }\n};\nint main(){ CuriousTab objCuriousTab( new CuriousTab(20, 40) ); objCuriousTab.Display(); }

Difficulty: Easy

Correct Answer: The program will print the output 20 40 .

Explanation:


Introduction / Context:
Here, instead of a standard copy constructor (CuriousTab(const CuriousTab&)), there is a custom constructor taking a pointer. Passing new CuriousTab(20,40) binds to that pointer-taking overload.


Given Data / Assumptions:

  • CuriousTab(CuriousTab objB) copies x and y from objB.
  • Display() prints x and y.
  • Memory leak of the heap object is irrelevant to the printed output but exists.


Concept / Approach:
Resolve overloads: constructing with a pointer selects the pointer-taking constructor, which dereferences fields and copies values.


Step-by-Step Solution:
1) new CuriousTab(20,40) creates a heap object with x=20, y=40.2) That pointer is passed to CuriousTab(CuriousTab), which assigns x=objB->x and y=objB->y.3) Display() prints 20 40.


Verification / Alternative check:
Replace the pointer-ctor with a reference copy-ctor and pass by value to observe identical printed values but without the leak.


Why Other Options Are Wrong:
Default constructor is not selected; there is no compile-time error since overload resolution succeeds; values are not garbage due to definite assignments.


Common Pitfalls:
Thinking this uses a copy constructor; it does not. Also forgetting to delete the heap object (memory leak).


Final Answer:
The program will print the output 20 40 .

Discussion & Comments

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