Home » C++ Programming » Questions and Answers » Question
  1. What is the output of this program?
    #include <iostream>
    #include <vector>
    using namespace std;
    class ComponentClass
    {
    public:
    virtual void traverse() = 0;
    };
    class LeafClass: public ComponentClass
    {
    int number;
    public:
    LeafClass(int num)
    {
    number = num;
    }
    void traverse()
    {
    cout << number << ' ';
    }
    };
    class CompositeClass: public ComponentClass
    {
    vector < ComponentClass * > children;
    public:
    void add(ComponentClass *ptr)
    {
    children.push_back(ptr);
    }
    void traverse()
    {
    for (int k = 0; k < children.size(); k++)
    children[k]->traverse();
    }
    };
    int main()
    {
    CompositeClass containers[6];
    for (int k = 0; k < 5; k++)
    for (int L = 0; L < 4; L++)
    containers[k].add(new LeafClass(k *4+L));
    for (int m = 1; m < 5; m++)
    containers[0].add(&(containers[m]));
    for (int n = 0; n < 5; n++)
    {
    containers[n].traverse();
    cout << endl;
    }
    }
    1. 4 5 6 7
    2. 8 9 10 11
    3. 12 13 14 15
    4. 16 17 18 19
    5. None of these
Correct Option: E

In this program, We are choosing and printing the numbers based on the certain limit and this is a composite design pattern.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
4 5 6 7
8 9 10 11
12 13 14 15
16 17 18 19



Your comments will be displayed only after manual approval.