i have a base class, 2 derived classes and an entitymanager class that has a container of base pointers pointing to derived objects. i have a virtual clone method in the base to take care of the copy constructors in the derived classes, but im having trouble wrapping my head around overloading the assignment operator and preventing slicing, could someone please help with that and perhaps review how ive handled the entitymanager copy constructor? i think its ok
class System
{
public:
virtual System* clone()=0;
};
class projectile :public System
{
public:
projectile* clone()
{
return new projectile(*this);
}
};
class player : public System
{
public:
player* clone()
{
return new player(*this);
}
};
class EntityManager
{
private:
vector<System*> theEntities;
public:
EntityManager(){}
EntityManager(EntityManager& other)
{
for (size_t i=0;i<other.theEntities.size();i++)
theEntities.push_back(other.theEntities[i]->clone());
}
void init()
{
projectile* aProjectile = new projectile;
player* aPlayer = new player;
theEntities.push_back(aProjectile);
theEntities.push_back(aPlayer);
}
};
int main (int argc, char * const argv[])
{
EntityManager originalManager;
originalManager.init();
EntityManager copyManager(originalManager);
return 0;
}
Add a
swapmember that swaps the containers, then implement assignment as copy and swap:The argument to the assignment operator will be copied using the copy constructor you’ve already written, then you swap the data, so the data that belonged to
*thiswill be destroyed when that parameter goes out of scope, and*thisowns the newly copied data.Re-using the copy constructor in this way means you only need to implement a correct copy constructor (and correct swap, which is usually easy to get right) and your assignment operator is really simple and automatically correct.
N.B. your
initmember and copy ctor are not exception safe, if anypush_backoperation throws an exception you leak memory. You’re also missing a destructor, but I assume that’s present in the real code.