class Player { public: Player(); Player(&Player) const; private: Item * item; } class Item { public: Item(); void virtual Use(); } class Sword : public Item { public: Sword(); void virtual Use(); } Player::Player() { item = new Sword(); } Player::Player(&Player p) { item = new Item(*(p.item)); } 

The player has a field of type "pointer to the object", which are usually assigned pointers to objects derived from the "object" classes - for example, the "sword". I need to copy the player, then call the Use () method of the item that is stored in the field. After a long sitting in the debugger, there was a feeling that the copy of the player when calling item-> Use () called the method of the parent class (empty).

  • 2
    First, make sure your code is compiled. And it would be good to see a minimal reproducible example . - αλεχολυτ
  • one
    Transferred to a comment: why do you have copy constructor with const ? How do you get something to copy, if you yourself prohibit changing the object? - isnullxbh
  • 1) The code in the original is many times more; here I have specially simplified it - it is needed only to demonstrate the question, i.e. and the answer was not expected in the form of a working code. 2) Const copy constructor, because the original object does not change. At least, it is written in the textbook, which is on my shelf. And I must admit, I have never experienced problems with them. - Narical

2 answers 2

Since, in fact, when copying, you need to keep the final type of the item, you cannot apply new Item(...) with any argument. To create a copy of an item you need to know its final type exactly. You can use the virtual constructor pattern aka cloning:

 class Item { public: Item(); virtual void Use(); virtual Item* Clone() const =0; virtual ~Item() {} } class Sword : public Item { public: Sword(); void Use(); Item* Clone() const { return new Sword (*this); } } Player::Player(const Player& p) { item = p.item->Clone(); } 
  • one
    Another virtual destructor in the Item should be added. - andy.37
  • Thank you so much for the answer, what you need! There is a virtual destructor in the original code, he wrote an example from his head and decided that to demonstrate the question, one can do without it. - Narical

Make for loyalty a special constructor that will call the inherited, and then copy the class fields. And call when copying it. Now you simply create another empty object of type Player.