ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
struct Base {
virtual void run() { step1(); step2(); }
virtual void step1() { cout << "B1 "; }
virtual void step2() { cout << "B2 "; }
};
struct Derived : Base {
void step1() override { cout << "D1 "; }
};
int main() {
Base *p = new Derived();
p->run();
}- A. B1 B2
- B. D1 B2
- C. D1 D1
- D. B1 D1
Correct answer: B. D1 B2
This is the template-method pattern: run() is inherited unchanged from Base, but its internal calls to step1() and step2() are both virtual. step1() dispatches to Derived's override (D1); step2() is not overridden by Derived, so it falls back to Base's own version (B2). Result: D1 B2.
More OOP with C++ and Java questions
- What is printed? java class Account { protected double balance; Account(double b) { balance = b; } void transfer(Account to, double amt) {…
- What is printed? cpp struct Base { Base() { cout << "Base "; } Base(int x) { cout << "Base(" << x << ") "; } }; struct Derived : Base {…
- What is printed? java class Node<T> { T value; Node<T> next; Node(T v) { value = v; } } public class Main { static <T> int length(Node<T>…
- What is printed? cpp struct Shape { virtual ~Shape() = default; }; struct Circle : Shape {}; struct Square : Shape {}; int main() { Shape…
- What is printed? java class Base { void process() { System.out.print("Base.process "); validate(); } protected void validate() {…
- What is printed? java class Base { public String toString() { return "Base[" + describe() + "]"; } protected String describe() { return…