3

This is a niche question, but I'm struggling to find a sufficient answer.

Struct members can be const, but can a function pointer/reference member be declared const? Based off my reading of C++17 section 9.3, I don't think so:

struct Ex {
  const int i;
  void (*pfn)(int i); // 1. can pfn be a const member?
  void (&rfn)(int i); // 2. can rfn be a const member?
};
0

1 Answer 1

5
  1. Yes:
    struct Ex {
        const int i;
        void (*const pfn)(int i); // 1. can pfn be a const member?
        void (&rfn)(int i);       // 2. can rfn be a const member?
    };
    
  2. It already is - You can't assign to a member referencing a function.
Sign up to request clarification or add additional context in comments.

5 Comments

Aah; My hangups were 1) void (const* pfn)(); is invalid syntax (what I tried), and 2) paranoia that the reference could be assigned to when without const. Thanks!
@JWCS Glad it helped! You're welcome!
@JWCS • The general rule is that const qualifies the thing to its immediate left. The exception to the rule is that if const appear first, it applies to the thing to its immediate right. Most learn the exception to the rule (which is encountered quite common), and not the general rule (which causes lots of consternation when encountered).
@Eljay Indeed. It took a long time before I saw code with "east const" and by then I had already gotten used to the exception. We're using it at work now though, so perhaps I'll learn to use it without thinking in some distant future :-)
TBH, I was really only testing the reference version; I naively assumed the same semantics for pointer/reference syntax. Tho, for the longest time, for consistency (C/C++), I advocated for const always on the rhs type const * const * const ... but with more modern c++, we barely use pointers anymore, so the team pivoted to always put const on the lhs of the type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.