C++ (constructor overload selection and copy construction) — determine the output printed after constructing Derived via two different constructors.\n\n#include<iostream.h>\nclass Base {\n int x, y;\npublic:\n Base() { x = y = 0; }\n Base(int xx) { x = xx; }\n Base(int p, int q = 10) { x = p + q; y = q; }\n void Display(void) { cout << x << " " << y << endl; }\n} objDefault(1, 1);\n\nclass Derived : public Base {\n Base obj;\npublic:\n Derived(int xx, int yy) : Base(xx, xx + 1) { }\n Derived(Base objB = objDefault) { }\n};\nint main() {\n Derived objD(5, 3);\n Derived *ptrD = new Derived(objD);\n ptrD->Display();\n delete ptrD;\n return 0;\n}\n\nWhat does the program print?

Difficulty: Hard

Correct Answer: 11 6

Explanation:


Introduction / Context:
This exercise probes C++ constructor resolution and object slicing versus copy construction. The class Derived has two user-declared constructors: one forwarding arguments to the Base subobject, and a second that takes a Base by value with a default argument. When we pass a Derived to new Derived(objD), which constructor is invoked and what state does the Base subobject hold when Display() is called?


Given Data / Assumptions:

  • Derived(int,int) builds a Base subobject via Base(xx, xx + 1).
  • Derived(Base) is a converting constructor taking Base by value and doing nothing in its body.
  • An implicit copy constructor Derived(const Derived&) is still generated by the compiler.
  • Display() prints the Base subobject of the object it is called on.


Concept / Approach:
Overload resolution chooses the best match. Passing a Derived to construct another Derived makes the implicit copy constructor an exact match, which is better than converting to Base and calling Derived(Base). Therefore, new Derived(objD) uses the copy constructor, not the Derived(Base) overload.


Step-by-Step Solution:

Construct objD(5,3): Base subobject uses Base(5,6) so x = 5 + 6 = 11, y = 6.Copy-construct *ptrD from objD: the Base subobject is copied, so it also has x = 11, y = 6.Call ptrD->Display(): prints 11 6.


Verification / Alternative check:
If you forcibly call the converting constructor (e.g., new Derived(static_cast(objD))) then the Base subobject in the new object would default-construct to 0 0 because the body does nothing and no base initializer is provided.


Why Other Options Are Wrong:

  • 3 2, 8 3, 11 10: Do not match the actual Base state produced by the constructors shown.
  • “Will not compile”: All declarations are valid in classic header context.


Common Pitfalls:
Assuming the presence of Derived(Base) suppresses the implicit copy constructor (it does not), or assuming the converting constructor will be chosen over the exact-match copy constructor.


Final Answer:
11 6

More Questions from Functions

Discussion & Comments

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