class Equipment
{
std::vector<Armor*> vEquip;
Weapon* mainWeapon;
int totalDefense;
int totalAttack;
public:
unsigned int GetWeight();
int * GetDefense();
bool EquipArmor(Armor* armor);
bool UnequipArmor(Armor* armor);
bool EquipWeapon(Weapon* wep);
bool UnequipWeapon(Weapon* wep);
Equipment();
virtual ~Equipment();
};
It seems like there should be no destructor. The vector of pointers will take care of itself when it goes out of scope, and the actual objects the pointers point to don’t need to be deleted as there will be other references to it.
All of the objects in this refer to the main Container:
class Container
{
int weightLimit;
unsigned int currWeight;
std::vector<Item*> vItems;
public:
bool AddItem(Item* item);
bool RemoveItem(Item* item);
Container();
Container(int weightLim);
Container(int weightLim, std::vector<Item*> items);
~Container();
};
Now here I can see it being necessary to delete all objects in the container, because this is where all the objects are assigned via AddItem(new Item(“Blah”))
(Armor and Weapon inherit from Item)
Non-pointer types will take care of themselves. So, ints, floats, objects, etc. will take care of themselves, and you don’t have to worry about deleting them.
Any pointers that are managed by the class need to be deleted by that class’ destructor. So, if the memory pointed to by the pointer was allocated in the class or if it was given to that class with the idea that that class would manage it, then the destructor needs to delete the pointer.
If the pointer is to memory that another class is managing, then you obviously don’t want your destructor to delete it. That’s the job of the class that is in charge of the memory pointed to by that pointer.
Standard containers do not manage the pointers that they hold if they hold pointers. So, if you have a container of pointers, whichever class is supposed to manage them needs to delete them. Odds are that that’s the class that holds the container, but that depends on what your code is doing.
So, typically, for a class that has a container of pointers, you’ll need something like this in the destructor:
Every pointer that has memory allocated to it has to have something (generally a class, but sometimes the function that it’s allocated in) who effectively owns that memory and makes sure that it is freed. When talking about classes, that’s usually the same class that the memory is allocated in, but of course, it’s quite possible for one class or function to allocate the memory and then effectively pass on the ownership of that memory to another class or function. Regardless, whoever “owns” the memory needs to deal with cleaning it up. That’s what your destructor needs to worry about: cleaning up any resources that that class owns.