Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does const mean following a function/method signature? [duplicate]

Tags:

c++

constants

According to MSDN: "When following a member function's parameter list, the const keyword specifies that the function does not modify the object for which it is invoked."

Could someone clarify this a bit? Does it mean that the function cannot modify any of the object's members?

 bool AnalogClockPlugin::isInitialized() const  {      return initialized;  } 
like image 622
Scott Avatar asked Oct 11 '09 04:10

Scott


People also ask

What does const mean in a function?

The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.

What does putting const at the end of a function mean?

const at the end of a function signature means that the function should assume the object of which it is a member is const . In practical terms it means that you ask the compiler to check that the member function does not change the object data in any way.

What does const method mean in C++?

The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).

What does const in front of a function mean?

const after member function indicates that data is a constant member function and in this member function no data members are modified.


2 Answers

It means that the method do not modify member variables (except for the members declared as mutable), so it can be called on constant instances of the class.

class A { public:     int foo() { return 42; }     int bar() const { return 42; } };  void test(const A& a) {     // Will fail     a.foo();      // Will work     a.bar(); } 
like image 81
Pierre Bourdon Avatar answered Oct 09 '22 18:10

Pierre Bourdon


Note also, that while the member function cannot modify member variables not marked as mutable, if the member variables are pointers, the member function may not be able to modify the pointer value (i.e. the address to which the pointer points to), but it can modify what the pointer points to (the actual memory region).

So for example:

class C { public:     void member() const     {         p = 0; // This is not allowed; you are modifying the member variable          // This is allowed; the member variable is still the same, but what it points to is different (and can be changed)         *p = 0;     }  private:     int *p; }; 
like image 30
blwy10 Avatar answered Oct 09 '22 16:10

blwy10