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();
}
  1. A. Group[Shape Group[] ]
  2. B. Group[Shape Group[]
  3. C. Shape Group
  4. 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

Exams that ask this topic