nik
nik

Reputation: 8725

What's the use of const here

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?

Upvotes: 2

Views: 302

Answers (7)

Pengzhi Zhou
Pengzhi Zhou

Reputation: 511

A const after function of a class, means this function would not modify any member objects of this class. Only one exception, when the member variable is marked with Mutable.

Upvotes: 0

jason
jason

Reputation: 241585

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.

Upvotes: 0

mmattax
mmattax

Reputation: 27660

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

Upvotes: 0

user207462
user207462

Reputation: 91

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

Upvotes: 0

Terry Mahaffey
Terry Mahaffey

Reputation: 11981

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

Upvotes: 0

Igor Zevaka
Igor Zevaka

Reputation: 76500

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.

Upvotes: 5

waterlooalex
waterlooalex

Reputation: 13872

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;
   }
}

Upvotes: 7

Related Questions