Vector of pointers doesn't work!

Hello! My program doesn't work, what is wrong with it? It crashes when calling a function.

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
#include <iostream>
#include <vector>

struct P
{
    virtual void func() { std::cout << "Parent" << std::endl; }
};

struct D : P
{
    void func() override { std::cout << "Derived" << std::endl; }
};

int main()
{
    int N = 2;

    std::vector<P *> elements;

    std::cout<<"Making pointers\n";

    P * parent;
    D * derived;

    std::cout<<"Inserting pointers\n";

    elements.insert(elements.end(), parent);
    elements.insert(elements.end(), derived);

    for ( int i = 0; i < N; i++ )
    {
        std::cout<<"calling "<<i<<" func\n";

        elements[ i ] -> func(); //Crash!
    }

    std::cout << "Enter a character to exit: "; char c; std::cin >> c;
    return 0;
}
Your pointers aren't initialized.
std::vector makes a copy of those pointers (they point to the same location) but there is no memory allocated.
So when calling elements[i]->func(); you try to call the function, but element[i] points outside of your memory space so your programm crashes.

Also note:
- elements contains a variable to get the size: elements.size()
use that to iterate through the elements instead of N (for ( int i = 0; i < elements.size(); i++ ) )
- std::vector contains a method to insert elements at the end: elements.push_back()

2 easy ways to solve this:
- allocate memory and initialize the pointer
1
2
P * parent = new P(); 
D * derived = new D();

- Or just create that pointers when appending the element vector
1
2
elements.push_back(new P());
elements.push_back(new D());
Last edited on
Topic archived. No new replies allowed.