Reputation: 3129
I am trying to check if the virtual function on an certain object instance is from a certain implementation. Intuitively it looks like the following code segment:
#include <cstdio>
using namespace std;
class A
{
public:
virtual void method()
{
printf("This is from A \n");
}
};
class B : public A
{
public:
virtual void method()
{
printf("This is from B \n");
}
};
int main()
{
B b;
b.method();
if (b.&method == &B::method)
{
printf("Horray! simple. \n");
}
return 0;
}
But obviously the line if (b.&method == &B::method)
doesn't work.
Can you kindly suggest how this should work? Thanks.
Upvotes: 1
Views: 364
Reputation: 238421
Can you kindly suggest how this should work?
In this trivial example, the member function pointer of an instance of B
obviously has the address of the member function of the class B
there is no point in testing this.
In general, if we had a pointer or reference to an instance of an unknown derived class, such test couldn't be written in standard C++. There is no way to get the address of the function to which a virtual call resolves at run time.
However, GCC does have an extension that allows you to do exactly that.
typedef int (*fptr)(A *);
fptr p = (fptr)(a.*fp);
Or, if the compiler documents the ABI that it uses, you may be able to use the specification to extract the address from the member function pointer.
Upvotes: 1