2

Possible Duplicate:
Meaning of “const” last in a C++ method declaration?

In the below function declaration,

const char* c_str ( ) const;  

what does the second const do ?

Community
  • 1
  • 1
ango
  • 829
  • 2
  • 10
  • 23

3 Answers3

18

It means the method is a "const method" A call to such a method cannot change any of the instance's data (with the exception of mutable data members) and can only call other const methods.

Const methods can be called on const or non-const instances, but non-const methods can only be called on non-const instances.

struct Foo {
  void bar() const {}
  void boo() {}
};

Foo f0;
f0.bar(); // OK
fo.boo(); // OK

const Foo f1;
f1.bar(); // OK
f1.boo(); // Error!
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

That const can only tag onto member functions. It guarantees that it will not change any of the object's data members.

For example, the following would be a compile-time error because of it:

struct MyClass
{ 
    int data; 
    int getAndIncrement() const;
};

int MyClass::getAndIncrement() const
{
    return data++; //data cannot be modified
}
chris
  • 60,560
  • 13
  • 143
  • 205
1

It is a modifier that affects that method (it is only applyable to methods). It means that it will only access, but not modify the state of the object (i.e., no attributes will be changed).

Another subtle change is that this method can only call other const methods (it would not make sense to let it call methods which will probably modify the object). Sometimes, this means that you need two versions of some methods: the const and the non-const one.

Baltasarq
  • 12,014
  • 3
  • 38
  • 57