KittyT2016
KittyT2016

Reputation: 195

is there a way to pass this as const?

I have a class of items and a function that returns it's size. I have the operator == which gets 2 const parameters of the class type and return the result of item1.size() == item2.size (). size function is non-parametres func and need only hidden this parameter.

The problem is when I try to use size on const reference of classes, it's give me an error:

'function' : cannot convert 'this' pointer from 'type1' to 'type2'

The compiler could not convert the this pointer from type1to type2.

This error can be caused by invoking a non-const member function on a const object. Possible resolutions:

    Remove the const from the object declaration.

    Add const to the member function.

The piece of code as it is on my problem:

bool operator==(const CardDeck& deck1, const CardDeck& deck2){
    if (deck1.size() != deck2.size()) {
        return false;
    }
    //...
}

The error:

 'unsigned int CardDeck::size(void)' : cannot convert 'this' pointer from 'const CardDeck' to 'Cardeck&'

If I want that size will get the object as const, I must make it friend and pass the object as const refference or is there a way to tell size get the class type this as constant ??? Thanks for helping.

Upvotes: 1

Views: 729

Answers (1)

Mark B
Mark B

Reputation: 96291

Most likely you forgot to qualify the size member function as const: size_t size() const { return /* compute/return size */; }

The alternative is that you really did typo CardDeck as Cardeck somewhere (the spelling from your error message).

Upvotes: 3

Related Questions