G
Gabriel de Dietrich
Hi all!
Just out of curiosity: Is there any way to get the address of a
particular virtual member function given an object? Some code to make
things more clear...
class A
{
public:
A() { }
virtual void f() { }
};
class B: public A
{
public:
B() { }
virtual void f() { }
};
typedef void (A::*FPtr)();
FPtr getFAddress(A* obj)
{
return &obj->f; // FIXME This won't compile (at least on VC++ 8)
}
int main()
{
A a;
B b;
getFAddress(&a); // Should return &A::f
getFAddress(&b); // Should return &B::f
}
The "intuituve" solution of this implementation of getFAddress
doesn't even compile on VC++ 8 (error C2276 if that matters). Note
that f is virtual, so the address depends on the object's class. Now,
if the compiler can generate the code to get the address of the right
f member, why can't we use this for our own code? (OK, this may lead
to lots of catastrophic code -- like the end of polymorphism as we
know it, but anyway...). I don't really think there is a portable
solution for this, but if someone has had this problem before, I'm
curious to see their solution.
Thanks,
Gabriel
Just out of curiosity: Is there any way to get the address of a
particular virtual member function given an object? Some code to make
things more clear...
class A
{
public:
A() { }
virtual void f() { }
};
class B: public A
{
public:
B() { }
virtual void f() { }
};
typedef void (A::*FPtr)();
FPtr getFAddress(A* obj)
{
return &obj->f; // FIXME This won't compile (at least on VC++ 8)
}
int main()
{
A a;
B b;
getFAddress(&a); // Should return &A::f
getFAddress(&b); // Should return &B::f
}
The "intuituve" solution of this implementation of getFAddress
doesn't even compile on VC++ 8 (error C2276 if that matters). Note
that f is virtual, so the address depends on the object's class. Now,
if the compiler can generate the code to get the address of the right
f member, why can't we use this for our own code? (OK, this may lead
to lots of catastrophic code -- like the end of polymorphism as we
know it, but anyway...). I don't really think there is a portable
solution for this, but if someone has had this problem before, I'm
curious to see their solution.
Thanks,
Gabriel