开发者

c++ const use in class methods [duplicate]

This question already has answers here: Closed 11 years ago.

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 using

const 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 { }

  1. The first const indicates that the return value is constant. In this particular case, it's not particularly relevant since the int is a value as opposed to a reference.
  2. The second const indicates the parameter obj is constant. This indicates to the caller that the parameter will not be modified by the function.
  3. The third const indicates the function myfunc 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜