Can I declare a non-member function (global function, may be) as const in C++? I understand that the const keyword actually is applied to the implicit "this" argument passed in member functions. Also since only member functions follow the "thiscall" calling convention, can const be applied for non-member functions?
Leaving aside what I am trying to do by declaring non-member function const, would compiler report error for doing so?
const function use cases A const function can be called by either a const or non- const object. Only a non- const object can call a non- const function; a const object cannot call it.
To make a member function constant, the keyword “const” is appended to the function prototype and also to the function definition header. Like member functions and member function arguments, the objects of a class can also be declared as const.
If the function is non-constant, then the function is allowed to change values of the object on which it is being called. So the compiler doesn't allow to create this chance and prevent you to call a non-constant function on a constant object, as constant object means you cannot change anything of it anymore.
Not in standard C, since there are no classes or objects (as in "class instances, i.e. collections of data with associated functions"), there's nothing for the function to be const "against".
No, only a non-static member function may be const
qualified.
What semantic would you expect from a const non-member function ? If you want to enforce that no parameters are modified by the function, just take them by const reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With