On Wed, 7 Mar 2007 08:32:08 +0100, "Per Inge Mathisen" <[EMAIL PROTECTED]> 
> Since we are apparently turning this thread into mental gymnastics
> anyway, I have a related C++ question. Can virtual functions be
> inlined? If not, that would certainly be a big performance cost
> compared to C code with inlining.

Long answer: 

Short answer:
You can declare every virtual function inline, whether the compiler obeys this 
depends on several things.
The first thing to know is that the compiler will have to make sure that no 
matter what polymorphism works. So as long as the compiler cannot know whether 
the object, on which the virtual function is called, is derived from the 
specified objecttype (i.e. the lowest allowed baseclass by for example a 
function parameter) or not it will use dynamic dispatch and call the function. 
This will have no significant difference in performance when compared to a 
regular function call (only two additional pointer dereferences). This will of 
course still leave you with the significant overhead of a function call.

So the only time when the compiler inlines a virtual function is when it _does_ 
know an objects *absolute* objecttype. This will be the case when using 
references rather than pointers (you cannot pass a Derived to a parameter 
Base&, so certainty is guaranteed). Further member or composite objects 
(through a pointer or not) that are initialized by the constructor's 
initialization list can usually be recognized by a good optimizer and as such 
calls on them can be inlined. Then lastly a local or a global-static object's 
type can always be known by the compiler and as such a call to those objects 
can always be inlined.

PS Maybe my short answer isn't as short as the FAQ entry ;-)


Warzone-dev mailing list

Reply via email to