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
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?
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.