c++ const use in class methods [duplicate]
Possible Duplicates:
What's the use of const here Using 'const' in class's functions
Hi All,
I keep making mistakes about the use of const with class methods and variables. For example, sometimes I fix problems usingconst int myfunc(const int &obj) const { }开发者_StackOverflow
some other times I feel I don't need const at the end since the parameter is already const, so I don't see why I should enforce this fact by appending a const at the end.
const int myfunc(const int &obj) const { }
- The first
const
indicates that the return value is constant. In this particular case, it's not particularly relevant since theint
is a value as opposed to a reference. - The second
const
indicates the parameterobj
is constant. This indicates to the caller that the parameter will not be modified by the function. - The third
const
indicates the functionmyfunc
is constant. This indicates to the caller that the function will not modify non-mutable member variables of the class to which the function belongs.
Regarding #3, consider the following:
class MyClass
{
void Func1() { ... } // non-const member function
void Func2() const { ... } // const member function
};
MyClass c1; // non-const object
const MyClass c2; // const object
c1.Func1(); // fine...non-const function on non-const object
c1.Func2(); // fine... const function on non-const object
c2.Func1(); // oops...non-const function on const object (compiler error)
c2.Func2(); // fine... const function on const object
Noel Llopis wrote a great chapter on const in C++ for Game Developers.
Take a look at his blog post http://gamesfromwithin.com/the-const-nazi for a good explanation of const.
The const at the end indicates the const'ness of a member variable with respect to a class. It indicates it does not change any of the state of a class. The const at the beginning indicates the const'ness of the type int.
精彩评论