C++ (dynamic allocation and character arithmetic) — determine the printed value from a constructor that sums an int and a character code.
#include
class CuriousTab {
int *p;
public:
CuriousTab(int xx, char ch) {
p = new int();
*p = xx + int(ch);
cout << *p;
}
~CuriousTab() { delete p; }
};
int main() {
CuriousTab objCuriousTab(10, 'B');
return 0;
}
What value is printed?
-
AThe program will print the output 76.
-
BThe program will print the output 108.
-
CThe program will print the output garbage value.
-
DThe program will report compile time error.
Answer
Correct Answer: The program will print the output 76.
Explanation
Introduction / Context:This snippet allocates an int on the heap, computes a sum using an integer literal and the numeric code of a character, and prints the result. Understanding how chars convert to int in C++ is the key here.
Given Data / Assumptions:
- xx = 10.
- ch = 'B', whose ASCII code is 66.
- The constructor does *p = xx + int(ch) and prints *p.
Concept / Approach:In C and C++, characters are small integer types. Converting a char to int yields its code point (commonly ASCII in this context). Therefore the arithmetic expression 10 + 66 evaluates to 76, which is then printed. Memory is correctly freed in the destructor, avoiding leaks.
Step-by-Step Solution:
1) Evaluate int(ch) for 'B' → 66.2) Compute 10 + 66 → 76.3) Store in *p and stream via cout → prints 76.Verification / Alternative check:Replace 'B' with 'a' (97) to see 107. Replace 10 with 0 to print the character code itself.
Why Other Options Are Wrong:
- 108: Would correspond to 42 + 66 or 10 + 98; not our inputs.
- Garbage value / compile error: Code is correct and deterministic.
Common Pitfalls:Expecting character concatenation semantics (like strings) instead of integer arithmetic with char.
Final Answer:The program will print the output 76.