What does const keyword mean in prototype C ++ function?

Possible duplicate:
What does const mean signifying a function / method?

I came across many features in my later readings in C ++ (especially Boost) that have a notation that I have never seen before. For example:

virtual void B() const; 

You can see that we have a constant after the function name! I saw the const keyword mainly on the return values โ€‹โ€‹of functions (or as parameters) regarding their use in functions, but this is different. Can someone explain to me what it is and why we use it? And also how different is this from the usual use of const on functions?

 int * const Function(int *const constantPointerToAnInteger, char const* pointerToAConstantChar); 
+7
source share
3 answers

When you have a const object, only member functions marked as const can be called. for example

 struct Silly { void say_hi(); void say_bye() const; }; // ... Silly const s; s.say_hi(); // illegal s.say_bye(); // legal 

In addition, a constant member function cannot change any member variables of an object (unless member variables change), for example

 struct Silly { int x; mutable int y; void do_stuff() const { x = 0; } // illegal - labelled const void do_other_stuff() const { y = 0; } // fine - y is mutable }; 
+15
source

This is a promise (mandatory), the function will not change any member of the class. Without this, you could only call it for const objects.

+5
source

Forbids a method to modify member variables of a class.

A good rule is to declare a method as const when it is assumed to be const (es. Getters) for at least two reasons:

  • documentation : it immediately shows that a call that this method is safe to provide
  • safety : error prevention

In any case, the method constant can be bypassed in two ways:

  • const_cast : remove persistence of an object
  • mutable fields: allow a specific member to change, even using the const method.
+3
source

All Articles