Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I declare a non-member function const in C++?

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?

like image 803
Sulla Avatar asked Dec 08 '10 11:12

Sulla


People also ask

Can we call non-const member function from const member function?

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.

Can a member function be const?

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.

What will happen if a const object calls a non-const member function?

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.

Does C have const functions?

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".


1 Answers

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.

like image 196
icecrime Avatar answered Oct 12 '22 14:10

icecrime