+ 40
Can non-constant variables access constant functions?
Since it doesn't work the other way around, I suspect it wont work either but it would save some work if it did e.g. not having to define the same function for both const and non const.
17 Antworten
+ 28
This is your case. Right?
const member function — add()
non-constant variable — sum
Edit: @ Kirk Schafer, thanks for the post, now the add() is a "const member" function ;)
https://code.sololearn.com/coFfqeMIeq7U/?ref=app
+ 13
Yes, nonconst objects can legally call const methods.
+ 9
@Rahul - I was curious about this (thanks for the code), then found a thread that says you cannot declare a non-member function const:
https://stackoverflow.com/questions/4387154/can-i-declare-a-non-member-function-const-in-c
So to check if the "const" was ignored, I copied your code into Godbolt:
https://godbolt.org/g/8oLMkp
The output assembly is the same whether "const int ..." is there or "int ..." -- implying the const is dropped (?) ... and it does not compile (there or on SoloLearn) if const trails the function definition like a member declaration.
error: non-member function 'int ...' cannot have cv-qualifier
...) const {
^~~~~
Am I missing something (clarification request)?
+ 8
But in const functions, you can't access non-constant variables and objects
+ 7
Constant Functions means that they will remain same throughout the execution of the program.
Non-constant variable are those whose value can be changed at any point during the execution of the program.
Therefore, Non constant variables can't be used because they change the behaviour of the function.
But why do you make the function constant ?
Even if you make it , Make one more function and call that constant function there and use it wisely there where you can use non-constant variable to make any number of changes you desire.
Making a function constant is not a good practice.
You must make only variables constant.
Hope you have understood well.
Even if there is any query , feel free to ask.
+ 5
ok
+ 5
Rahul
Nice update :) I still don't get a difference at Godbolt (in the final assembly) unless 'const' is placed after the function name:
int add() const {
...
}
Then the assembly changes these two lines, adding "const":
23: Compute::add() const:
56: call Compute::add() const
+ 5
@ Kirk Schafer, Thanks again!
Now, it is showing the const keyword: https://godbolt.org/g/QS6dqq
+ 3
speshal wan
+ 2
of course they can. inside constant function you can decide the non constant values
+ 2
non constant variables are functions. functions inside functions. normal. i think....
+ 1
nice
+ 1
Yes they can
+ 1
Напишу по русски☺
+ 1
yes👍
0
Yes And No. In This One, Random Times Are No.
0
Fake Times Are Yes.