Const object in C ++

I have a question about permanent objects. In the following program:

class const_check{ int a; public: const_check(int i); void print() const; void print2(); }; const_check::const_check(int i):a(i) {} void const_check::print() const { int a=19; cout<<"The value in a is:"<<a; } void const_check::print2() { int a=10; cout<<"The value in a is:"<<a; } int main(){ const_check b(5); const const_check c(6); b.print2(); c.print(); } 

void print() is a constant member function of the const_check class, so according to the definition of constants, any attempt to change int a should lead to an error, but the program works fine for me. I think I have some confusion here, can someone tell me why the compiler doesn't put this as an error?

+4
source share
4 answers

By writing

 int a = 19; 

inside print() , you declare a new local variable a . This has nothing to do with the int a you declared inside the const_check class. It is said that a member variable is obscured by a local variable. And it’s quite normal to declare local variables in the const function and change them; the value of const applies only to the fields of the object.

Try to write

 a = 19; 

and you will see an error message.

+20
source

You do not change the instance variable a , you create a local variable a in each method.

+4
source

You do not change the member variable a in print () or print2 (). You declare a new local variable a, which obscures the member variable a.

+1
source

Also, if I'm not mistaken, you forgot to actually declare a member variable const.

-1
source

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


All Articles