unj2
unj2

Reputation: 53552

Error Writing a Copy constructor in C++

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;
    }

Upvotes: 2

Views: 6020

Answers (3)

Luchian Grigore
Luchian Grigore

Reputation: 258688

1) You declared your copy constructor explicit (do you need it to be explicit?), so the correct syntax is

Critter aCritter3 (aCritter2);

not

Critter aCritter3 = aCritter2;

2) Also, the proper signature for an assignment operator is:

Critter& operator=(const Critter& rhs);

3) The method GetHungerLevel should be const, but you don't need to use it - you can just write:

this->hungerLevel = rhs.hungerLevel;

Upvotes: 4

alexm
alexm

Reputation: 6882

add const qualifier to GetHungerLevel()

  int GetHungerLevel() const {return hungerLevel;}  

Upvotes: 2

Steve Jessop
Steve Jessop

Reputation: 279455

You need int GetHungerLevel() const {return hungerLevel;}

Otherwise, you aren't allowed to call GetHungerLevel() using the reference-to-const rhs.

Also, you can't do copy-initialization with an explicit copy 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.

Upvotes: 4

Related Questions