0

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

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.

Community
  • 1
  • 1
Bob
  • 10,741
  • 27
  • 89
  • 143

3 Answers3

5

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
Matt Davis
  • 45,297
  • 16
  • 93
  • 124
4

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.

bkersten
  • 316
  • 2
  • 6
0

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.

Peter Oehlert
  • 16,368
  • 6
  • 44
  • 48