1

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.

KittyT2016
  • 195
  • 9
  • 2
    Did you make `CardDeck::size() const`? – Galik Jan 10 '16 at 20:32
  • As I understand to make it const means to make it's parameters const, and here it get's only this. to write const CardDeck::size() only means that the returned value (not by reference but only copy of it) will be const, which doesn't mean anything, am I wrong ? That's why I asked if there is a way to tell the compiler that this is constant for the method size. – KittyT2016 Jan 10 '16 at 20:35
  • You make the whole function `const` by adding the `const` keyword after the function declaration but before its body. Nothing to do with return type or parameters. – Galik Jan 10 '16 at 20:40
  • Possible duplicate of [c++ error C2662 cannot convert 'this' pointer from 'const Type' to 'Type &'](http://stackoverflow.com/questions/12068301/c-error-c2662-cannot-convert-this-pointer-from-const-type-to-type) – default Jan 10 '16 at 21:08

1 Answers1

3

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).

Mark B
  • 95,107
  • 10
  • 109
  • 188