Const at the end of a function declaration in C ++

Possible duplicate:
The value of "const" in a C ++ method declaration?

In the function declaration below

const char* c_str ( ) const; 

what does the second constant do?

+2
source share
3 answers

This means that the method is a "const method". Calling such a method cannot change any of the instance data (except for members of mutable data) and can only call other const methods.

Const methods can be called on instances of const or non-const, but non-const methods can be called only 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! 
+15
source

That const can only tag on member functions. It ensures that it does not change any of the data elements of the object.

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

 struct MyClass { int data; int getAndIncrement() const; }; int MyClass::getAndIncrement() const { return data++; //data cannot be modified } 
+1
source

This is a modifier that affects this method (it applies only to methods). This means that it will be available, but does not change 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 be pointless to allow it to call methods that are likely to modify the object). Sometimes this means that you need two versions of some methods: const and not const .

+1
source

Source: https://habr.com/ru/post/916435/


All Articles