Search code examples
c++templates

How to declare a list with different classes that all have the same function?


I'm currently learning c++ and got stuck on the following problem:

I have unknown number of different classes that all have the same function:

class A {
    doStuff();
}
class B {
    doStuff();
}
class C {
    doStuff();
}

There is a function that creates a single one of these classes with the help of templates:

template<class T>
auto createClass(T classToCreate) {
    return make_shared<classToCreate>();
}

And I have a second function that's supposed to start the function "doStuff" within every object.

Is there a way to create a list or something else that I can iterate through so that I can keep the process dynamic?

I'm not sure what I have to search for to find a solution.


Solution

  • This appears a useful place for an abstract (pure virtual) base class. It defines an interface the derived class must implement, but not any of the implementation details.

    class I {
    public:
        virtual void doStuff() = 0;
    };
    
    class A : public I {
    public:
        void doStuff() override {
            std::cout << "A\n";
        }
    };
    
    class B : public I {
    public:
        void doStuff() override {
            std::cout << "Class B\n";
        }
    };
    
    class C : public I {
        int x;
    public:
        C(int x) : x(x) { }
     
        void doStuff() override {
            std::cout << x << "\n";
        }
    };
    

    You can now ensure that the object received by a function implements this functionality.

    void foo(I *obj) {
        if (obj) obj->doStuff();
    }