W.F. W.F. - 1 month ago 4
C++ Question

Why can't one use scope resolution with member pointer dereference?

Consider a simple example:

struct FooParent {
virtual void bar() { }

struct Foo: FooParent {
void bar() { }

int main() {
Foo foo;
void (Foo::*foo_member)() = &FooParent::bar;

As you can see one can use scope resolution on the
object when calling bar member function while there is no way to explicitly declare the scope for member function pointer. I accept that the syntax should be prohibited when using
as the operator can be overloaded in sometimes unexpected way, but I cannot understand the reason behind preventing explicit scope resolution when dereferencing with

I am trying to disable virtual dispatch for a member pointer that points to a base class's virtual function.


The name of the variable you declared is foo_member, inside your local block scope. It is not a name Foo::foo_member, i.e. the class Foo has no member foo_member. By contrast, the name bar lives in the scope of the class Foo, and also in the scope of the class FooParent.

So the scope resolution mechanism works as expected: it resolves the scope.

[Update:] There is no mechanism to disable virtual dispatch through a member function pointer. You can call a member function of the base subobject like this:

 void (FooParent::*p)() = &FooParent::bar;

But the call still ends up getting dispatched virtually. The virtuality of the member function is baked into the member function pointer value. The next best thing you can do is to use a lambda:

auto q = [](FooParent & f) { f.FooParent::bar(); };