ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Shape {
public:
    virtual void draw() const = 0;
};
class Group : public Shape {
    vector<Shape*> children;
public:
    void add(Shape* s) { children.push_back(s); }
    void draw() const override {
        for (auto* c : children) c->draw();
    }
};
class Dot : public Shape {
    int id;
public:
    Dot(int i) : id(i) {}
    void draw() const override { cout << "Dot" << id << " "; }
};
int main() {
    Group g;
    g.add(new Dot(1));
    Group inner;
    inner.add(new Dot(2));
    inner.add(new Dot(3));
    g.add(&inner);
    g.draw();
}
  1. A. Dot1 Dot2 Dot3
  2. B. Dot2 Dot3 Dot1
  3. C. Dot1 Dot3 Dot2
  4. D. Compilation error: cannot add a Group* where Shape* is expected

Correct answer: A. Dot1 Dot2 Dot3

This is the Composite pattern: Group IS-A Shape, so &inner (a Group*) is legally added as a Shape* child. g.draw() iterates its children virtually: Dot(1) draws itself, then the nested Group (inner) recursively draws its own children in order, Dot(2) then Dot(3): "Dot1 Dot2 Dot3".

More OOP with C++ and Java questions

Exams that ask this topic