Vector, polymorphism and destructors.

Hello there. I have a class which inherits from another one and a vector to store pointers to the objects
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
vector<Worker*> workers;

class Worker
{
    private:
        string name;
        int age;
        double salary;
    public:
        ...
}

class boss_Worker : Worker
{
    private:
        int people_under;
        string responsible_for;
}

boss_Worker::boss_Worker(string n, int a, double s, int p, string r) : Worker(n, a, s)
{
    people_under = p;
    responsible_for=r;
}


Now, when I make a new object I do something like
workers.push_back(new boss_Worker(data, data, data...))

As you see I use the "new" thingy now I am wondering how should I/where should I insert the delete (in a destructor or where) and how to do it. Greetings
With a vector, it's tricky. You'll need to do it before the vector is destroyed.

A loop like this will suffice:

1
2
3
4
5
while(!workers.empty())
{
  delete workers.back();
  workers.pop_back();
}


Do that before 'workers' goes out of scope. If 'workers' is owned by another class, it could go in that class's destructor. If it's just owned by a function (like main), then it could go before you return from the function.

Also, if you will be removing individual elements from the vector, be sure to delete them before you actually remove them.


If you can use boost, there was a nifty ptr_vector class which automatically deletes elements. If you use that you don't have to worry about this. (IMO boot's ptr containers are one of the most useful areas of that lib.)
Thanks a lot for your help Disch! Unfortunately I cannot use boost in this given task.
So, if I want to remove an individual element by using workers.erase(i) do I need to run the delete beforehand?
Last edited on
Or, if the vector is managing the lifetime of it's elements, consider pushing back a unique_ptr or shared_ptr to the object so that you don't have to manually delete them yourself.
cire's suggestion is also good. I would consider doing that as well.

So, if I want to remove an individual element by using workers.erase(i) do I need to run the delete beforehand?


Yes.
Topic archived. No new replies allowed.