an error I don't understand

Hi guys,
I'm trying to understand an error that I get while trying overload '==' operator.
The error I get is:
error C2662: 'Check::getName' : cannot convert 'this' pointer from 'const Check' to 'Check &'

Here's the code:

1
2
3
4
5
bool Check:: operator==(const Check&) const{
	if((this->getName()==getName()) && (this->getId()==getId()))
		return true; 
	return false;
}



Cheers
It's hard to know for sure, because you've decided to withhold the line number of the line that's generating the error, and also to withhold the rest of your code.

But since you obviously want us to play some bizarre guessing game, my guess is that the statements this->getName()==getName and this->getId()==getId()

(a) violate the constness of your operator==, and

(b) make no sense whatsoever, because this->getName() is the same as getName().

I'd guess that getName() or/and getId() is not a const function like your operator==(...)

By the way: That comparison makes no sense. It is compared with itself hence it will always return true.
fixed it to:
1
2
3
4
5
6
 
bool Check:: operator==(const Check& p) const{
	if((this->getName()==p.getName()) && (this->getId()==p.getId()))
		return true; 
	return false;
}


still get this error.
Coder, why getName() and gerId() has to const for this overloading to work?

Thanks
Last edited on
Coder, why getName() and gerId() has to const for this overloading to work?
you cannot call a non const function from a const function. That would break constness (like MikeyBoy said)
why getName() and gerId() has to const for this overloading to work?

Because that's the whole point of a const method - that you can't modify the state of the object within the method. And to enforce this, you are restricted to only calling const methods.

But this method only compares few fields and it won't change a thing, this is why it is called as const method.
Right. So why is calling non-const methods?

EDIT: The point is that the compiler doesn't necessarily know that those methods you're calling don't change the object. The only way to be sure is to disallow all calls to non-const methods.

But, again, this is all based on guesses, because you're still refusing to show us your code.
Last edited on
Oh, I got it now. I'm using get_something() function in order to read private fields in "Check" class. If those method are not private, then the private fields will be change- breaking the encapsulation principle.

Thanks guys!
It doesn't matter whether they're private or not - they have to be const if you're going to call them from within a const method (or operator).
Yes, you're right, I just noticed another mistake of mine(didn't make the get_something() function as const methods).

Cheers and thanks.
You're welcome :)
Topic archived. No new replies allowed.