C++ object lifetime: constructor prints "Curious", destructor prints "Tab" — what is the output?
#include
class CuriousTab {
public:
CuriousTab() { cout << "Curious"; }
~CuriousTab() { cout << "Tab"; }
};
int main() {
CuriousTab objTab; // automatic object
return 0; // destructor runs at scope end
}
-
AThe program will print the output Curious.
-
BThe program will print the output Tab.
-
CThe program will print the output CuriousTab.
-
DThe program will report compile time error.
Answer
Correct Answer: The program will print the output CuriousTab.
Explanation
Introduction / Context: This question checks understanding of automatic storage duration and the order of constructor/destructor calls in C++. Output is produced first by the constructor and then by the destructor when the object goes out of scope at the end of main.
Given Data / Assumptions:
- Constructor writes "Curious".
- Destructor writes "Tab".
- objTab is a local object in main.
Concept / Approach: For an automatic object, construction occurs upon entering the block and destruction occurs on leaving it. Thus, the concatenated stream shows constructor text followed by destructor text without a newline: "CuriousTab".
Step-by-Step Solution:
Enter main → construct objTab → prints "Curious".Exit main → destroy objTab → prints "Tab".Final combined output: CuriousTab.Verification / Alternative check: Allocating with new would print only the constructor text unless delete is called; here, automatic storage ensures destructor runs.
Why Other Options Are Wrong:
- Curious or Tab alone: ignores either construction or destruction.
- Compile error: code is valid with classic headers.
Common Pitfalls: Expecting a newline or space between outputs; misunderstanding when destructors execute for automatic variables.
Final Answer: The program will print the output CuriousTab.