What is the use of const here

at

int salary() const { return mySalary; }

as far as I understand const for this pointer, but I'm not sure. Can someone tell me that const is used here?

+2
source share
7 answers

It looks like you have the right idea, in C ++ const by the method of the object means that the method cannot change the object.

For example, this will not be allowed:

class Animal {
   int _state = 0;

   void changeState() const { 
     _state = 1;
   }
}
+7
source

When a function is marked const, it can be called in the const pointer / link of this class. Essentially, he says. This function does not change the state of the class .

+5
source

const. , - const. :

const foo bar;
bar.m();

, m const, .

0

, const; - this .

0

, () . IE, const.

0

A const after a class function means that this function will not change any member objects of this class. Only one exception when a member variable is marked Mutable.

0
source

All Articles