tags:

views:

121

answers:

6

in

int salary() const { return mySalary; }

as far as I understand const is for this pointer, but I'm not sure. Can any one tell me what is the use of const over here?

Thanks

+7  A: 

Sounds like you've got the right idea, in C++ const on a method of an object means that the method cannot modify the object.

For example, this would not be allowed:

class Animal {
   int _state = 0;

   void changeState() const { 
     _state = 1;
   }
}
Alex Black
This syntax is only valid for C++0x
ergosys
Which syntax? I haven't typed any C++ in a while, so perhaps I got something slightly wrong, no guarantees it compiles, but overlooking any mistakes I'm sure you get the general idea, and the general idea is part of regular C++.
Alex Black
I could be mistaken, I was using MSVC++ version 6 (years ago), perhaps it didn't conform to the spec, does Microsoft ever do anything like that? ;)
Alex Black
Under C++-98: §9.3.3: "A nonstatic member function may be declared const, volatile, or const volatile. These cv-qualifiers affect the type of the this pointer (9.3.2)." Therefore, that code snippet should produce an error.
greyfade
I was referring to the instance member initialization, this is new for C++0x.
ergosys
Alex has been doing C#, I'd guess. But the idea is the same.
Hans Passant
@ergosys: ah, thanks. I've been doing C# and Scala recently, the C++ knowledge is getting overwritten!
Alex Black
A: 

It's a const method. It means that it won't modify the member variables of the class nor will it call non-const methods. Thus:

const foo bar;
bar.m();

is legal if m is a const method but otherwise wouldn't be.

Jason
+5  A: 

When the function is marked const it can be called on a const pointer/reference of that class. In effect it says This function does not modify the state of the class.

Igor Zevaka
A: 

It means that function can be called on a const object; and inside that member function the this pointer is const.

Terry Mahaffey
A: 

It just guarantees that calling salary() doesn't change the object state. IE, it can be called with a const pointer or reference.

A: 

It's a const member function. It's a contract that the function does not change the state of the instance.

more here: http://www.fredosaurus.com/notes-cpp/oop-memberfuncs/constmemberfuncs.html

mmattax