Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling the override function in a vector (C++) [duplicate]

I'm having trouble trying to call the override function of an object that was appended to a vector. I'm not quite sure if I just don't completely understand pointers and references, so I'm not quite sure what to look for when debugging this issue.

Here is my code:

#include <iostream>
#include <vector>

class Task {
    public:
        Task(std::vector<Task> *list) {
            list->push_back(*this);
        }

        virtual void Run() {
            std::cout << "Called Task Run!" << std::endl;
        }
};

class OverrideTask : public Task {
    public:
        OverrideTask(std::vector<Task> *list) : Task(list) {}
        void Run() override {
            std::cout << "Called Override Run!" << std::endl;
        }
};

int main() {
    std::cout << "Main method entered" << std::endl;
    std::vector<Task> listOfTasks;

    OverrideTask ot = OverrideTask(&listOfTasks);
    Task t = Task(&listOfTasks);

    for(int i = 0; i < listOfTasks.size(); i++) {
        listOfTasks[i].Run(); // Will print "Called Task Run!" twice.
    }

    ot.Run(); // Prints "Called Override Run!"
    t.Run(); // Prints "Called Task Run!"
}

When I loop through the vectors, it seems that I can't call the override function, but when I call them directly from the object, they seem to work. Can anybody point me in the correct direction?

like image 386
liver man Avatar asked Apr 02 '26 05:04

liver man


1 Answers

Try store the base pointer in the vector instead like this. @Christophe asked me to remind that we store pointers which means the Task object must remain alive. See also also @Quimby's note about using unique_ptr instead of Task *.

#include <iostream>
#include <vector>

class Task {
    public:
        Task(std::vector<Task *> *list) {
            list->push_back(this);
        }

        virtual void Run() {
            std::cout << "Called Task Run!" << std::endl;
        }
};

class OverrideTask : public Task {
    public:
        OverrideTask(std::vector<Task *> *list) : Task(list) {}
        void Run() override {
            std::cout << "Called Override Run!" << std::endl;
        }
};

int main() {
    std::vector<Task *> listOfTasks;
    OverrideTask ot = OverrideTask(&listOfTasks);
    Task t = Task(&listOfTasks);
    for(int i = 0; i < listOfTasks.size(); i++) {
        listOfTasks[i]->Run();
    }
} 

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!