C++ (const member function) — does a const-qualified Show() print the initialized member value?
#include
class Tab {
int x;
public:
Tab();
void Show() const;
~Tab() {}
};
Tab::Tab() { x = 5; }
void Tab::Show() const { cout << x; }
int main() {
Tab objB; objB.Show();
return 0;
}
Predict the output.
-
AThe program will print the output 5.
-
BThe program will print the output Garbage-value.
-
CThe program will report compile time error.
-
DThe program will report runtime error.
Answer
Correct Answer: The program will print the output 5.
Explanation
Introduction / Context:This checks whether a const-qualified member function can read and print a data member that was assigned in the constructor. It reinforces the difference between reading (allowed in const methods) and writing (disallowed) to members.
Given Data / Assumptions:
- Constructor sets x = 5.
- Show() is declared const and prints x.
- Destructor is trivial and defined inline.
Concept / Approach:A const member function promises not to modify any non-mutable data members. Reading x and sending it to cout is legal. Since x is assigned in the constructor, its value is well-defined when Show() executes.
Step-by-Step Solution:
1) Construction: x becomes 5.2) Show() reads x and writes to cout.3) Therefore the output is 5.Verification / Alternative check:Marking Show() non-const would not change behavior here. Attempting to modify x inside Show() would fail to compile due to const qualification.
Why Other Options Are Wrong:
- Garbage value: x is initialized deterministically.
- Compile/runtime error: No rule is violated.
Common Pitfalls:Assuming const methods can’t even read members or forgetting to initialize members before use.
Final Answer:The program will print the output 5.