I am trying to write a copy constructor for a class but I get these two error messages, which I cannot decipher. Can somebody please tell me what I am doing incorrect?
class Critter
{
public:
Critter(){}
explicit Critter(int hungerLevelParam):hungerLevel(hungerLevelParam){}
int GetHungerLevel(){return hungerLevel;}
// Copy Constructors
explicit Critter(const Critter& rhs);
const Critter& operator=(const Critter& rhs);
private:
int hungerLevel;
};
Critter::Critter(const Critter& rhs)
{
*this = rhs;
}
const Critter& Critter::operator=(const Critter& rhs)
{
if(this != &rhs)
{
this->hungerLevel = rhs.GetHungerLevel(); // ERROR: object has type qualifier not compatible with member function
}
return *this;
}
int _tmain(int argc, _TCHAR* argv[])
{
Critter aCritter2(10);
Critter aCritter3 = aCritter2; // ERROR : No suitable copy constructor
Critter aCritter4(aCritter3);
return 0;
}
You need
int GetHungerLevel() const {return hungerLevel;}Otherwise, you aren’t allowed to call
GetHungerLevel()using the reference-to-constrhs.Also, you can’t do copy-initialization with an
explicitcopy constructor, only direct initialization:Critter aCritter3(aCritter2);Probably you want to make the copy ctor non-explicit rather than necessarily change the definition of
aCritter3, but your call.