ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Stack {
    vector<int> data;
public:
    void push(int x) { data.push_back(x); }
    int pop() {
        int top = data.back();
        data.pop_back();
        return top;
    }
    bool empty() const { return data.empty(); }
};
int main() {
    Stack s;
    s.push(1); s.push(2); s.push(3);
    string result;
    while (!s.empty()) result += to_string(s.pop());
    cout << result;
}
  1. A. 123
  2. B. 321
  3. C. Compilation error: Stack has no default constructor for vector
  4. D. Empty output

Correct answer: B. 321

Elements are pushed 1,2,3 (3 on top). pop() repeatedly removes the LAST element (back()): first 3, then 2, then 1, building the string "3"+"2"+"1" = "321".

More OOP with C++ and Java questions

Exams that ask this topic