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();
}- A. Dot1 Dot2 Dot3
- B. Dot2 Dot3 Dot1
- C. Dot1 Dot3 Dot2
- 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
- What is printed? java class Base { public int hashCode() { return 1; } } class Derived extends Base { @Override public int hashCode() {…
- What is printed? java class Base { Base self() { return this; } } class Derived extends Base { @Override Derived self() { return this; }…
- What is printed? java class Account { private double balance; Account(double b) { balance = b; } void withdraw(double amt) { if (amt >…
- What is printed? java class Task { void execute() throws Exception { try { riskyStep(); } catch (RuntimeException e) { throw new…
- What is printed? cpp class Base { public: virtual void op() { cout << "Base::op "; } void callOp() { this->op(); } }; class Derived…
- What is printed? cpp struct Base { virtual std::string name() const { return "Base"; } }; struct Derived : Base { std::string name() const…