Search code examples
c++constantsfunction-pointersc++03pointer-to-member

How do I Declare a Method Pointer That's Constant


1st off this isn't a question about how to point to a constant method. I want to know how to make my method pointer constant.

Given:

struct foo {
    void func1();
    void func2();
};

I can construct a method pointer with void (foo::*bar)() = &foo::func1 but I can later do bar = &foo.func2 and I want to prevent that.

I can easily do this with const auto bar = &foo::func1, but I'm not sure how to do this pre .


Solution

  • All you have to do is to add the const keyword after the *, like this:

    void(foo::*const _pointer)() = &foo::func1;