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;
}- A. 123
- B. 321
- C. Compilation error: Stack has no default constructor for vector
- 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
- What is printed? java interface Repository<T> { void save(T item); T find(int id); } class UserRepository implements Repository<String> {…
- What is printed? cpp class Printable { public: virtual void print() const = 0; virtual ~Printable() = default; }; class Report : public…
- What is printed? java class Shape implements Comparable<Shape> { double area; Shape(double a) { area = a; } public int compareTo(Shape o)…
- What is printed? java class Base { public Object process() { return "base-result"; } } class Derived extends Base { @Override public…
- What is printed? cpp class Logger { public: static Logger& instance() { static Logger inst; return inst; } void log(const string& msg) {…
- What is printed? java class EventBus { private static EventBus instance; private EventBus() { System.out.print("created "); } public…