tags:

views:

310

answers:

4

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;
 }
+7  A: 

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();
}
Pierre Bourdon
Could you clarify "constant instances?" Maybe with a little code?
Scott
Scratch that. Looks like you provided some code after all.
Scott
You'll want to read up about C++ const-ness. You'll need to use const_iterator's on const STL objects, etc.
nall
Indeed, const-correctness is very important to understand and practice.
GMan
Also, const methods can only call static or other const methods.
Steve Guidi
Minor correction: The method _promises_ to not to change the object. (There's syntactic constructs allowing you to circumvent this promise. Of course, using them usually is gross - but they're there and there is a reason for that.)
sbi
+2  A: 

The compiler won’t allow a const member function to change *this or to invoke a non-const member function for this object

sat
+1  A: 

As answered by @delroth it means that the member function doesn't modify any memeber variable except those declared as mutable. You can see a good FAQ about const correctness in C++ here

Naveen
+3  A: 

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;
};
blwy10
Good point. It's the difference between const-pointer-to-int, pointer-to-const-int and const-pointer-to-const-int. const methods make the pointer const.
UncleBens
You probably mean "...member variables _not_ marked as mutable...".
sbi
Oops, haha. Sorry about that.
blwy10