Why use the const function?

I am trying to understand the functions of the getters and seters class ...

My question is: If I create a function that simply gets only the state from its class (the "getter" function), why should it be designated as "member-member function"? I mean, why use the const member function if my function is not intended to change any decencies of its class? I do not understand, please: (

eg:

int GetValue() {return a_private_variable;}

and

int GetValue() const {return a_private_variable;}

What is the real difference?

+4
source share
3 answers

When you declare a member function constsuch as in

int GetValue() const;

then you tell the compiler that it will not change anything in the object.

, - . const, , const. - - const , .

, const -, , .

int GetValue() const;
int GetValue();

.

+8

const ++.

1:

const Object obj1;

  • obj1 - const. , . - const,

int GetValue() const {return a_private_variable;}

2:

int myMethod() const {//do something}

  • const. - const, ​​ . , const.

3:

int myMethod(const Object &x) {//do something with x}

  • , const. , myMethod -, x. , . .

, ; , , . , const , . , , ++ const. , . , -, C/++ .

+2

const const.

const , , .

In your case, the functions do exactly the same thing, but it doesn't have to be that way.

0
source

Source: https://habr.com/ru/post/1658240/


All Articles