Copy constructor and destructor in c++

1
2
3
4
5
6
7
8
9
Class Car{
  Private:
    string* _ID;
    bool _isFaulty;
    int _location;
    int _timer;
    int _order;
    vector<Road*> _roadPlan;
} 


I want to implements Copy constructor (deep copy) and destructor, and I don't know how to treat the vector of pointers (Road is an object too)
It's my first time with c++. Any help would be greatly appreciated!

Mor

Another thing, maybe I'll prefer using List instead of Vector, so i would like to see an implements of Copy constructor and destuctor with List too,
Thank you!!!
Last edited on
*edited to format snippet

One way is to loop through the right hand side vector and and copy construct a new Road whose address you push onto the left hand side vector

1
2
for (vector<Road *>::const_iterator ci = rhs._roadPlan.begin(); 
      ci != rhs._roadPlan.end(); ++ci) _roadPlan.push_back(new Road(*(*ci)));

Or you could try fooling around with initializer_list...
Last edited on
And what about the destructor? need to loop too or:
1
2
3
4
5
Car::~Car(){
  cout << "Delete Car" << endl;
  delete _ID;
  delete _roadPlan;
}

this is enough?

tnx!!
You'll need to loop too. Also, you can't just delete _roadPlan, it's an object (a vector) not a pointer.

you'll need to loop through and delete each pointer it holds, and if you're finicky also call vector::erase() for each one (or wait til the loop is done and call vector::clear())

Your code is gone (bad form), so I can't see how _ID is used, but I doubt it needs to be a pointer.

Also try not to start variable names with underscore (_), many system entities start their variable names that way, and you're more likely to have a name-clash with one of them.
Topic archived. No new replies allowed.