2

I've read:

How can a C++ base class determine at runtime if a method has been overridden?

and

get the real address(or index in vTable) of virtual member function

and the answers really bug me. Suppose there's a class MyClass, with some subclasses inheriting it; and that I have a MyClass* p = get_ptr_to_a_myclass().

Now, if I am able to invoke a virtual member, i.e. write p->Method() - how can it be that I can't get the address, or the address offset, of the Method method of *p? That is just inconsistent! After all, the condition for being able to invoke a function is being able to resolve/obtain its address (and knowing its signature etc.)

Please help me resolve this conundrum.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 3
    The way I see it: the information is there, but is accessible to the implementation i.e. to the compiler only, is not accessible at a language level to the user. It's the same as the information about about the size of an array allocated with `new[]`. The number of elements is available (in some instances) for `delete[]` to properly call destructors on all objects, but is not available for the user. – bolov Jul 03 '22 at 22:08
  • Just seems another example of C++ not having reflection. – SoronelHaetir Jul 03 '22 at 23:44
  • The base class can't detect if a virtual function has been over-ridden because the standard doesn't support a way to do so. Generally speaking, if a base class NEEDS to DETECT such a thing, then the design of that base class is flawed (and the programmer faces more serious problems than the base class not being able to detect if one of its virtual functions is over-ridden). – Peter Jul 04 '22 at 05:59
  • @Peter: I didn't say the base class needs such detection. In my scenario, my code is where both the base and child classes are used. – einpoklum Jul 04 '22 at 06:59
  • @SoronelHaetir: But this is not reflection. It is nothing other than the support for virtual methods. I'm not asking for information about _what_ has overridden the base class method - just for the address that I'm using anyway to call that method. – einpoklum Jul 04 '22 at 07:00
  • @einpoklum No, but being able to obtain distinct addresses for the two would require there to be an observable/measurable difference between them. In the case of virtual functions, the standard specifies that `p->Method()` (where `Method()` is virtual) resolves to a call of the most derived `Method()`. It does NOT specify how an implementation achieves that, and doesn't require the implementation to make relevant information available to the program. – Peter Jul 04 '22 at 14:24
  • @Peter: I see; it just seems nonsensical to me that this should be the case. It's like saying that `function()` should call a function, but `&function` could not be used. – einpoklum Jul 04 '22 at 18:21

0 Answers0