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; }
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.
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.
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).
const after member function indicates that data is a constant member function and in this member function no data members are modified.
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(); }
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; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With