A * a = new B();
a->foo();
Suppose B derives A and foo() is a virtual function. This example is quite frequent, the problem is that in some places it is said that compiler won't attempt to inline this, where in other places the exact opposite is stated.
I personally do not see a reason why this call could not be inlined, because it is quite easy to tell in compile time which function is getting called.
Edit 1: I am aware of the "general case", and am also aware that the compiler takes many factors to decide whether to inline or not. The question would be probably better formed if I asked if the compiler might inline this particular call.
The reason I am asking this is this particular quote from this C++ FAQ which says:
When the object is referenced via a pointer or a reference, a call to a virtual function cannot be inlined, since the call must be resolved dynamically.
If the compiler can somehow deduce that the object pointed by a is an instance of B (i.e. if the code is trivial, like in your example), then it could devirtualize the call - although it is not required to do so.
But the point is that, in general, the call is resolved at run-time, because you don't know (and neither does the compiler!) what is the dynamic type of the object pointed to by a.
In other words, if the compiler does not know what is the dynamic type of *a, and consequently does not know which foo() function should be called until run-time, it is impossible to devirtualize the call and inline it at compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With