0

bool operator==(const point& other) const

What is purpose of const two times? first const is to indicate that other (object of class point) is not going to be modified from the == overloaded function. This is what compiler guarantees. Last const suggest that this function does not modify anything from point class data member for object on which this == operator is called. This allows us to call == on constant objects as well. i.e. using == on p1 in below code will not work if second const is not there in overloaded operator. https://code.sololearn.com/cpf71rhwB2qw Is there anything else I am missing on the two const mentioned in overloaded operator? Feel free to ask for any clarification on question.

6th Aug 2022, 6:15 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 Answers
+ 2
Yes that and making sure that the function doesn't change the data members of the class, doing so sometimes opens the gate for some optimisations that the compiler can perform on it.
9th Aug 2022, 12:23 AM
Arsenic
Arsenic - avatar
+ 2
By doing p1 == p2 You are basically calling P1.operator== (p2); Now as you have correctly pointed the fact in your question that the last const suggests the function does not modify anything from the class, and hence we can call it on const objects of the class ( which have const *this pointer ) The case is similar to calling a non-const function from a const object. As soon as we remove the const qualifier from the member functions, there is no way to guarantee the const-correctness of the function and thus an error is raised when we try to pass "const *this" to the function.
6th Aug 2022, 6:35 AM
Arsenic
Arsenic - avatar
+ 2
Let me try to simplify things If a member function is not const, it means it is allowed to change the data members on tha object, and calling it with a constant object would destroy the purpose of making the object constant at first place, hence the compiler throws an error when we try to do the same. https://code.sololearn.com/c2s0jUA2JN0G/?ref=app
8th Aug 2022, 1:04 AM
Arsenic
Arsenic - avatar
+ 1
I am sorry but could you please elaborate? When we pass const *this and gets error ? Any scenario which asks us to pass const this to member function?
6th Aug 2022, 10:12 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Okay... thanks a lot
9th Aug 2022, 5:53 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Yeah corect... got it...thanks But the main purpose of second const is to allow function call from const obj.... This is the only purpose...right ? Or any other need it fulfills ?
8th Aug 2022, 5:46 AM
Ketan Lalcheta
Ketan Lalcheta - avatar