2

Possible Duplicate:
Calling base class definition of virtual member function with function pointer

Given the following hierarchy:

struct Base
{
  virtual void f() = 0;
};

void Base::f()
{
  cout << "Base::f\n";
}

struct Derived : Base
{
  void f()
  {
    cout << "Derived::f\n";
  }
};

We can force a call to Base::f like so:

Derived d;

d.Base::f();

or:

Base * b = &d;

b->Base::f();

No surprises there. But is it possible to obtain a member function pointer through which Base::f can be called?

void (Base::*bf)() = &Base::f;

for_each( b, b+1, mem_fn( bf ) ); // calls Derived::f

(For the record, I don't actually have a need to do this. I'm just curious.)

Community
  • 1
  • 1
Andrew Durward
  • 3,771
  • 1
  • 19
  • 30

1 Answers1

2

As James McNellis commented the short answer is just "no".

The longer answer is, "if you're willing to accept some formal UB, then":

#include <iostream>
#include <algorithm>    // for_each
#include <functional>      // mem_fn
using namespace std;

struct Base
{
  virtual void f() = 0;
};

void Base::f()
{
  cout << "Base::f\n";
}

struct Derived : Base
{
  void f()
  {
    cout << "Derived::f\n";
  }
};

int main()
{
    struct DirtyHack: Base
    {
        void baseF() { Base::f(); }
    };

    Derived d;
    void (Base::*bf)() = static_cast< void(Base::*)() >( &DirtyHack::baseF );
    Base* b = &d;

    (b->*bf)();
    for_each( b, b+1, mem_fn( bf ) ); // calls Base::f
}

I wouldn't do this, but then, I would generally not use raw member function pointers anyway (bound ones are a different matter, e.g. for GUI events).

Note that if you control the Base class, then you can just factor out the functionality that you want to be accessible non-overridden.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331