Search code examples
c++parent

Use child method from the parent class c++


Here's the deal. Imagine your as follows bellow. After loading the files to the algorithm layer I want to be able to apply the 4 different algorithms. So the Algorithm class has 4 children and I want to do something like this:

int main(int argc, char* argv[]) {
    Data *data = new Data();
    Parent *alg = new Parent(data);

    alg->start();

    //and this will call the start methods defined in each child. 
}

The children are like this:

class Child1: public Parent {
public:
   int start();
}

class Child2: public Parent {
public:
   int start();
}
//etc...

And what I do in the Parents start() method is this:

int Parent::start() {
    Child1::start();
    Child2::start();
    //etc....
    return 0;
}

But I'm getting a 'cannot call member function 'Child1::start()', etc.. without object.' Can this thing be done somehow? Calling a child method from the parent class?


Solution

  • Take a look at the "Gang of Four" composite pattern:

    The Child classes should not be derived from the Parent class. Instead, Child and Parent classes should implement the same Interface, let's call it IAlgorithm. This Interface should have a pure virtual method start()...

    Here is an example (using C++11 auto and Range-based for loop):

    #include <iostream>
    #include <vector>
    
    /* parents and children implement this interface*/
    class IAlgorithm {
    public:
       virtual int start() = 0;
    };
    
    class Parent : public IAlgorithm {
    private:
        std::vector<IAlgorithm*> children;
        
    public:
        void addChild(IAlgorithm* child) {
            children.push_back(child);
        }
    
        int start() {
            std::cout << "parent" << std::endl;
            for (auto child: children)
                child->start();
            return 0;
        }
    };
    
    class Child1 : public IAlgorithm {
    public:
        int start() {
            std::cout << "child 1" << std::endl;
            return 1;
        }
    };
    
    class Child2 : public IAlgorithm {
    public:
        int start() {
            std::cout << "child 2" << std::endl;
            return 2;
        }
    };
    
    class Child3 : public IAlgorithm {
    public:
        int start() {
            std::cout << "child 3" << std::endl;
            return 3;
        }
    };
    
    int main()
    {
       Parent parent;
       Child1 child_1;
       Child2 child_2;
       Child3 child_3;
       
       parent.addChild(&child_1);
       parent.addChild(&child_2);
       parent.addChild(&child_3);
       
       parent.start();
       
       return 0;
    }
    

    The output:

    parent
    child1
    child2
    child3