Looping though a vector of abstract classes.

When i try to call a function from a pointer while looping trough a vector of pointers the program crashes("App.exe is not responding!").

declared in header:

1
2
3
4
5
6
7
class Graphics {
public:
...
private:
...
}
static ResourceManager* resources;


initialized in some function:

1
2
3
renderables = vector<Renderable*>();
MainUI ui = MainUI(); // class MainUI: public Renderable
registerRenderable(dynamic_cast<Renderable*>(&ui));


looped through:

1
2
3
4
5
6
 long delta = timer.getDelta();
        for (vector<Renderable*>::iterator iterator = renderables.begin(); iterator != renderables.end(); ++iterator) {
            Renderable *renderable = (*iterator); // Crashes here
            renderable->update(delta);
            renderable->render();
        }


renderable.h :

1
2
3
4
5
6
7
class Renderable
{
public:
    virtual void update(long delta) = 0;
    virtual void render() = 0;
    virtual void destroy() = 0;
};
Last edited on
The problem is somewhere else, this code works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <memory>

class Base {
public:
    virtual ~Base() {}
    virtual void print() = 0;
};
class Object : public Base {
public:
    void print() { std::cout << "Object" << std::endl; }
    
    ~Object() { std::cout << "dtor" << std::endl; }
};

int main()
{
    std::vector<Base*> data;
    data.push_back(new Object());
    data.push_back(new Object());
    data.push_back(new Object());
    data.push_back(new Object());
    data.push_back(new Object());
    
    for(auto iter = data.begin(); iter != data.end(); ++iter) {
        Base* temp = *iter;
        temp->print();
    }

// don't forget to clean up the mess
    for(auto& iter : data)
        delete iter;
    data.clear();
    
    return 0;
}

Last edited on
What does std::make_unique and std::unique_ptr?
std::unique_ptr is a c++11 class for automatic memory management
Don't mix it up with using normal pointers that should have ownership!

I adjusted the example so that i don't use any smart pointers
Last edited on
The problem was here:

1
2
3
renderables = vector<Renderable*>();
MainUI ui = MainUI(); // class MainUI: public Renderable
registerRenderable(dynamic_cast<Renderable*>(&ui));


Replaced with

1
2
renderables = vector<Renderable*>();
registerRenderable(new MainUI());
so you check the vector in an other scope?
If that's true it makes sense, if not it doesn't
Topic archived. No new replies allowed.