Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How compiler make's sure that no data member state is changed in the const member function? (either in C++ or java)

Tags:

c++

constants

How can a C++ or Java compiler make sure that none of the member variables state is changed in a const member function (mutable is exceptional).

Will the compiler do something like putting the code in a non-writable code segment or something like that?

like image 967
Suman Avatar asked Apr 20 '11 12:04

Suman


2 Answers

The compiler doesn't make sure. It can't, since there's no rule in the language that says that member variable state cannot change in a const member function. The only rule is that you cannot change the state through the this pointer (without casting away const).

like image 187
James Kanze Avatar answered Sep 20 '22 13:09

James Kanze


For C++ const checking is done at compile time through the logic of the compiler. It will ensure that if a function is marked const then no changes will be made to the member variables. I don't think it has anything to do with the storage of the executable code.

For Java, I wasn't aware that there was the same const paradigm.

like image 38
Nick Avatar answered Sep 19 '22 13:09

Nick