*(ref.pistol)
is accessing a Gun
instance, so the code is trying to call Gun
's copy constructor, but you have not defined one explicitly. You defined a non-default non-copy constructor only, so the compiler may omit creating a default copy constructor. You can explicitly define your own copy constructor, though:
class Gun{
private:
int bullet;
public:
Gun(int bnum) : bullet(bnum) { }
Gun(const Gun& ref) : bullet(ref.bullet) { }
};
Or, in C++11 and later:
class Gun{
private:
int bullet;
public:
Gun(int bnum) : bullet(bnum) { }
Gun(const Gun& ref) = default;
};
Either way, you can use it like this (don't forget that pistol
can be NULL, so you have to check for that in your Police
copy constructor):
class Police{
private:
Gun * pistol;
public:
Police(int bNum) {
if(bNum>0)
pistol = new Gun(bNum);
else
pistol=NULL;
}
Police(const Police& ref) {
if (ref.pistol)
pistol=new Gun(*(ref.pistol));
else
pistol=NULL;
}
~Police() {
delete pistol;
}
};
And don't forget to apply similar logic to the copy assignment operator as well (when dealing with manual deep copy implementations, don't forget the rule of 3, and the rule of 5 in C++11 and later):
class Gun{
private:
...
public:
...
// the implicit operator is sufficient in this particular example,
// this is being shown just for demonstation purposes...
Gun& operator=(const Gun& ref) {
bullet = ref.bullet;
return *this;
}
// or, in C++11 and later
//Gun& operator=(const Gun& ref) = default;
};
class Police{
private:
...
public:
...
Police& operator=(const Police& ref) {
if (ref != *this) {
delete pistol;
pistol = NULL;
if (ref.pistol)
pistol=new Gun(*(ref.pistol));
}
return *this;
}
// alternatively:
/*
Police& operator=(const Police& ref) {
if (ref != *this) {
if (pistol) {
if (ref.pistol) {
*pistol = *(ref.pistol);
return *this;
}
delete pistol;
pistol = NULL;
}
if (ref.pistol)
pistol=new Gun(*(ref.pistol));
}
return *this;
}
*/
};