ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
struct Shape {
virtual void draw() const { cout << "Shape "; }
};
struct Group : Shape {
std::vector<Shape*> children;
void add(Shape *s) { children.push_back(s); }
void draw() const override {
cout << "Group[";
for (auto *c : children) c->draw();
cout << "] ";
}
};
int main() {
Group g;
g.add(new Shape());
g.add(new Group());
g.draw();
}- A. Group[Shape Group[] ]
- B. Group[Shape Group[]
- C. Shape Group
- D. Compile-time error: Group cannot contain pointers to its own type
Correct answer: A. Group[Shape Group[] ]
This is the Composite design pattern. g.draw() prints Group[ then iterates children: the first, a plain Shape, prints Shape; the second, an empty Group, prints Group[] (its own empty draw). Finally g's own draw() closes with ] , giving Group[Shape Group[] ] .
More OOP with C++ and Java questions
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; } }; struct C : B {…
- Does this compile? java public class Main { public static void main(String[] args) { try { throw new RuntimeException("x"); } catch…
- What is printed? java public class Main { public static void main(String[] args) { try { Object[] arr = new String[3]; arr[0] = 100; }…
- What is printed? cpp void f() { try { throw 10; } catch (double d) { cout << "double:" << d; } catch (int i) { cout << "int:" << i; } }…
- What is printed? java public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3}; try {…
- What is printed? java class Base { final void secure() { System.out.print("Base.secure"); } } class Derived extends Base { // void…