2

I have an abstract interface I in which virtual void Foo() is defined, along with other functions. There are some subclasses in which Foo is re-defined, and others in which Foo is not. Now, given I* pi, is it possible to know whether Foo is re-defined? That is, I want to know whether pi->Foo() would call I::Foo() or X::Foo() where X is some type in which Foo is re-defined. I think this can be done by comparing function pointers, between &I::Foo and &pi->Foo, but not sure exactly how to. Note that I don't know the concrete type of pi in runtime, so I cannot compare function pointers directly by &I::Foo != &X::Foo.

ADD: So, a lot of people pointed that the design is bad, against the concept of abstraction and virtual functions. The main reason that I'm doing this is to bypass empty function calls to improve speed. Since some of Foo() are empty, I would like to remove it from a vector of pis, when Foo() is empty.

xosp7tom
  • 2,131
  • 1
  • 17
  • 26

2 Answers2

1

You can't find out from &pi->Foo, since, as the GCC error message will tell you,

ISO C++ forbids taking the address of a bound member function to form a pointer to member function.

If you want to know the type of an object at runtime, use typeid. Otherwise, rethink your design.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1

You can dynamic_cast your pointer to each of the child types that overrides Foo and if it's one of those types it will call the child. You can't take the address of a member function using the -> syntax you want to use.

But all that said I would really rethink your design before doing something like this. The point of interfaces and virtual methods is to avoid the need to know what type you're dealing with!

Mark B
  • 95,107
  • 10
  • 109
  • 188