Good evening, I've a question about the copy constructor, in particular how can it manage dynamic resources?
For example I've written some code in order to better explain my doubt : given the following Character, Backpack and Item class
class Character
{
public:
Character() { std::cout << "Character Constructor " << this << std::endl; }
Character(const Character & other) : inventory(other.inventory) {
std::cout << "Character Copy Constructor " << this << std::endl;}
~Character() { std::cout << "Character Destructor " << this << std::endl; }
private:
Backpack inventory;
};
class Backpack {
public:
Backpack() { std::cout << "I'm an backpack " << this << std::endl ; }
Backpack(const Backpack& other) : items(other.items) { std::cout << "I'm a backpack duplicated " << this << std::endl ; }
~Backpack() { std::cout << "Backpack Destroyed " << this << std::endl ; }
private:
Item items[3];
} ;
class Item
{
public:
Item() { std::cout << "I'm an item " << this << std::endl; }
Item(const Item &) { std::cout << "I'm an item duplicated " << this << std::endl; }
~Item() { std::cout << "Item Destroyed " << this << std::endl; }
private:
};
This version of the code works fine and dandy, but when I try to go from Item items[3]; to Item* items = new Item[3]; the whole program breaks down and all my tentatives to make it call the item copy constructor have failed and most cause leaks. Any tips? TT.TT
Edit. This is the version of "Backpack.hh" I'm trying to fix
class Backpack
{
public:
Backpack()
{
items = new Item[3];
std::cout << "I'm an backpack " << this << std::endl;
}
Backpack(const Backpack &other) : items(other.items)
{
items = new Item[3];
for (int i = 0; i < 3; i++)
items[i] = other.items[i];
std::cout << "I'm a backpack duplicated " << this << std::endl;
}
~Backpack()
{
delete[] items;
std::cout << "Backpack Destroyed " << this << std::endl;
}
private:
Item *items;
};
Also in order to test my code I did a main.cc file
#include "Character.hh"
using namespace std;
int main(){
Character Char1;
cout << endl;
Character Char2(Char1);
cout << endl;
return 0;
}