C++ inheritance with float and char: what does the following print after casting a computed float to char and then to int?
#include
class CuriousTabBase { public: float x; };
class CuriousTabDerived : public CuriousTabBase
{
public:
char ch;
void Process() { ch = (int)((x = 12.0) / 3.0); }
void Display() { cout << (int)ch; }
};
int main()
{
CuriousTabDerived *objDev = new CuriousTabDerived;
objDev->Process();
objDev->Display();
return 0;
}
-
AThe program will print the output 4.
-
BThe program will print the ASCII value of 4.
-
CThe program will print the output 0.
-
DThe program will print the output garbage.
-
EIt prints 52 because '4' ASCII is 52.
Answer
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:
xis set to 12.0 and divided by 3.0 ⇒ 4.0.- Result is cast to
int(→ 4) and assigned toch. 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.