C++ inheritance with float and char: what does the following print after casting a computed float to char and then to int?\n\n#include<iostream.h>\nclass CuriousTabBase { public: float x; };\nclass CuriousTabDerived : public CuriousTabBase\n{\npublic:\n char ch;\n void Process() { ch = (int)((x = 12.0) / 3.0); }\n void Display() { cout << (int)ch; }\n};\nint main()\n{\n CuriousTabDerived *objDev = new CuriousTabDerived;\n objDev->Process();\n objDev->Display();\n return 0;\n}

Difficulty: Easy

Correct Answer: The program will print the output 4.

Explanation:


Introduction / Context:
This question verifies understanding of casts and character storage. A float is computed, cast to int, stored in a char, and later printed after casting the char back to int.


Given Data / Assumptions:

  • x is set to 12.0 and divided by 3.0 ⇒ 4.0.
  • Result is cast to int (→ 4) and assigned to ch.
  • Display() prints (int)ch, not the character literal.


Concept / Approach:
Because the integer value 4 is stored in the char and then printed as an integer, the output is the number 4, not the ASCII code for the glyph '4' (which would be 52).


Step-by-Step Solution:
Compute 12.0 / 3.0 = 4.0.Cast to int ⇒ 4; assign to ch.Print (int)ch ⇒ 4.


Verification / Alternative check:
Compare cout << ch (character) versus cout << (int)ch (integer value) to see the difference.


Why Other Options Are Wrong:
Options B/E confuse the numeric value 4 with the ASCII code for the character '4'. Options C/D are inconsistent with the explicit calculation and casts.


Common Pitfalls:
Assuming characters always print as glyphs; an explicit cast to int prints the numeric value.


Final Answer:
The program will print the output 4.

More Questions from Objects and Classes

Discussion & Comments

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