pointer to virtual function of a base class

S

Steffen Jahn

Hi,

I'm looking for a way to get the pointer to a virtual function of
a base class. That is, I want to force an object to call the
virtual function of a base class. A direct call is no problem, but
I can't find a way to get the right function pointer.

Below is a simple example to describe my problem. -- It's only here
to illustrate the problem. My real implementation uses callback
templates. -- Help is highly appreciated.

Thank you!
Steffen

#include <iostream>

using std::endl ;
using std::cerr ;

struct B {
virtual void f() const { cerr << "B" << endl ; }
} ;

struct C : public B {
virtual void f() const { cerr << "C" << endl ; }
} ;

int main(int argc, char *argv[])
{
C *c = new C ;
c->B::f() ; // direct call: prints "B"
void (B::*g)() const = &B::f ;
(c->*g)() ; // prints "C", but I want "B", so how to set up g?
return 0 ;
}
 
K

Karl Heinz Buchegger

Steffen said:
int main(int argc, char *argv[])
{
C *c = new C ;
c->B::f() ; // direct call: prints "B"
void (B::*g)() const = &B::f ;
(c->*g)() ; // prints "C", but I want "B", so how to set up g?

c is still a pointer to a C object. Thus the virtual call
is dispatched to class C.
If you want the function from class B, then you have to make c
into a B pointer:

C* c = new C;
B* b = c;

...

(b->*g)();

Or of course you could use a cast to do the very same.
 
R

Ron Natalie

Steffen Jahn said:
I'm looking for a way to get the pointer to a virtual function of
a base class.

No, doesn't matter how you form the pointer to member, the
virtual function overriding is applied after the member pointer
is evaluated.
 
S

Steffen Jahn

No, doesn't matter how you form the pointer to member, the
virtual function overriding is applied after the member pointer
is evaluated.

That seems to be right. And I can follow this because it's simply
an offset into the vtable.

Anyways, since the compiler can resolve "c->B::f()" in the desired
way, there might be also a way to get the the address (pointer) of
this function. Anyone has an idea?

Thanks
Steffen
 
R

Ron Natalie

Anyways, since the compiler can resolve "c->B::f()" in the desired
way, there might be also a way to get the the address (pointer) of
this function. Anyone has an idea?

NO. I told you before. It is not possible (at least not portably).
The standard doesn't tell you how the code gets to the actual
executable instructions, just that it happens after the member
function pointer is dereferenced.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,141
Messages
2,570,818
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top