C++ (const member function) — does a const-qualified Show() print the initialized member value? #include<iostream.h> 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.

Difficulty: Easy

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.

More Questions from Constructors and Destructors

Discussion & Comments

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