Sulla
Sulla

Reputation: 8019

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?

Upvotes: 24

Views: 11434

Answers (2)

MSalters
MSalters

Reputation: 179779

To answer your second question: an attempt to use the member function syntax for a non-member (i.e. void foo() const; ) is a grammar violation. Therefore, a compiler must give a diagnostic - either an error or a warning. It may not silently ignore the const. However, it may report a warning, then pretend the const wasn't there and produce an executable.

Upvotes: 3

icecrime
icecrime

Reputation: 76745

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.

Upvotes: 25

Related Questions