Re: when EXACTLY is virtual mechanism used?

From: Andrey Tarasevich (andreytarasevich_at_hotmail.com)
Date: 01/31/04


Date: Sat, 31 Jan 2004 12:18:11 -0800

Sensorflo wrote:
> struct CBase
> { virtual inline void foo() { puts("base"); }
> };
> void main()
> { CBase obj;
> (&obj)->foo(); // static call or
> } // dynamic (using virtual table) call ?
>
> Is it compiler dependend, or does the standart say anything about
> wheter the static or the dynamic call is used? With Visual C++ 5.0,
> the call is static.

The standard doesn't say anything about any "static" or "dynamic" calls.
When it comes to non-qualified calls, the standard simply says that when
you call a non-virtual member function, the concrete function is chosen
in accordance with _static_ type of the object expression. When you call
a virtual member function, the concrete function is chosen in accordance
with _dynamic_ type of the object expression. That's all there is to it.

What steps compilers take in order to satisfy this requirement is
completely up to their implementers. They may decide to use dynamic
calls for _all_ member function calls, as long as the above requirements
are met (and vice versa). If in some situation they are sure that they
can correctly resolve a call to virtual function without using a dynamic
call - they are free to do so.

> I am asking because I thought that dynamic calls are used in
> connection with pointers or references, and (&obj) is a pointer. I
> know that the compiler can be smart enough to see that the dynamic
> type of the pointer (&obj) will be CBase, and thus use the more
> efficient static call.

Yes, that's entirely possible. It depends on the compiler's capabilities
to detect such situations.

> But I'm curious anyway. What does the standart say about it? In
> exactly which cases is the call dynamic?

The standard doesn't go into implementation details in this case.
There's no reason for it to do so.

-- 
Best regards,
Andrey Tarasevich


Relevant Pages