I have this base class:
class LevelPlayer
{
protected:
int level;
int id;
public:
LevelPlayer():id(-1){}
LevelPlayer(int level,int id):level(level),id(id){}
virtual ~LevelPlayer()=default;
LevelPlayer(const LevelPlayer&)=default;
LevelPlayer& operator=(const LevelPlayer&)=default;
};
and this derived class:
class GroupPlayer: public LevelPlayer
{
private:
IdPlayer* ptr;
public:
GroupPlayer():LevelPlayer(),ptr(nullptr){}
GroupPlayer(int level,int id,IdPlayer* ptr):LevelPlayer(level,id),ptr(new IdPlayer(*ptr)){}
~GroupPlayer()override=default;
GroupPlayer(const GroupPlayer&);
GroupPlayer& operator=(const GroupPlayer&);
};
and for the copy ctor of the derived one I wrote this:
GroupPlayer::GroupPlayer(const GroupPlayer& player):ptr(new IdPlayer(*(player.ptr))){}
but I am not sure if it's correct ... should I also add LevelPlayer(player)
?
CodePudding user response:
Looking at the constructors and seeing
ptr(new IdPlayer(*ptr))
ptr(new IdPlayer(*(player.ptr)))
I come to the conclusion, you don't need the pointer the default and the copy constructor. Make the member and the second constructor
IdPlayer player;
GroupPlayer(int level, int id, const IdPlayer& player): LevelPlayer(level, id), player{player} {}
instead of IdPlayer* ptr;
and remove other constructors. Finally, use spaces after punctuation marks in the code, this makes reading and code selection much easier.
CodePudding user response:
I am not sure if it's correct ... should I also add
LevelPlayer(player)
?
Yes, the derived class copy constructor needs to call the base class copy constructor explicitly:
GroupPlayer::GroupPlayer(const GroupPlayer& player)
: LevelPlayer(player), ptr(new IdPlayer(*(player.ptr)))
{
}
Since you have implemented the derived class copy constructor, and the base class constructor takes an input parameter, you need to pass in a value for that parameter. If you don't, the base class default constructor will be called instead, and thus level
and id
won't be copied from player
.