The 2024 Wheel Reinvention Jam is in 16 days. September 23-29, 2024. More info

Virtual function's disadvantage and real-life examples

I assume if you're asking if it it makes two unrelated pointers equal, not addresses of pointers. And yes, it does. And that's why it is an option - you can disable if you don't like hit.

Not sure what are you asking about my example? How can ptr() point anywhere than big() function? Look at the disassembly - there's no way it can point into middle of foo() and still return value 100000.


Replying to longtran2904 (#25776)

Oh sorry, my bad. Not your example, I mean something like this:

int Foo() { return 1000; }
int Bar()
{
    DoSomeOtherThing();
    return Foo();
}
// Some other place
int (*f)(void) = CheckSomething() ? Foo : SomeOtherFunction; // Can this point to the end of Bar?


Edited by longtran2904 on
Replying to mmozeiko (#25777)

I'm not aware of compilers doing such optimization. While technically it would be possible, my guess why that is not happening is because of multiple reasons:

  1. many targets/architectures require function prolog/epilog code, which means Foo() beginning must have specific bytes (saving frame pointer register) which would not happen in your Bar()

  2. optimizer often will rearrange code - mixing code for DoSomeOtherThing() and Foo(), so having Foo() directly at end of function is less likely to happen

  3. compiler would need to remember exactly which functions end at which places - and then search for them every time function pointer is used. This can be become very expensive in large programs


Edited by Mārtiņš Možeiko on
Replying to longtran2904 (#25778)