Possible Duplicates:
c++ const use in class methods
Meaning of “const” last in a C++ method declaration?
int operator==(const AAA &rhs) const;
This is a operator overloading declaration. Why put const
at the end? Thanks
Possible Duplicates:
c++ const use in class methods
Meaning of “const” last in a C++ method declaration?
int operator==(const AAA &rhs) const;
This is a operator overloading declaration. Why put const
at the end? Thanks
The const
keyword signifies that the method isn't going to change the object. Since operator==
is for comparison, nothing needs to be changed. Therefore, it is const
. It has to be omitted for methods like operator=
that DO modify the object.
It lets the compiler double-check your work to make sure you're not doing anything you're not supposed to be doing. For more information check out http://www.parashift.com/c++-faq-lite/const-correctness.html.
Making a method const
will let a contant object of the class to call it. because this method cannot change any of the object's members (compiler error).
It may deserve mention that const
is a part of the method's signature, so in the same class you may have two methods of the same prototype but one is const and the other isn't. In this case, if you call the overloaded method from a variable object then the non-const method is called, and if you call it from a constant object then the const
method is called.
However, if you have only a const
method (there is no non-const overload of it), then it's called from both variable and constant object.
For Example :
#include <iostream>
using std::cout;
class Foo
{
public:
bool Happy;
Foo(): Happy(false)
{
// nothing
}
void Method() const
{
// nothing
}
void Method()
{
Happy = true;
}
};
int main()
{
Foo A;
const Foo B;
A.Method();
cout << A.Happy << '\n';
B.Method();
cout << B.Happy << '\n';
return 0;
}
Will output :
1
0
Press any key to continue . . .
"const" at the end of any c++ declaration tells the compiler that it won't change the thing it belongs to.
That marks the method itself as being constant, which means the compiler will permit you to use the method whenever you have a const reference to the relevant object. If you have a const reference, you otherwise can only invoke methods that are also declared as const.
A 'const' at the end of a method declaration marks that method as being safe to call on a constant object.