Reputation: 12279
Suppose that situation:
struct base
{
void method()
{
requisites();
do_it();
}
virtual void requisites() const = 0;
void do_it() { /* do it */ }
};
struct derived : base
{
void requisites() const
{
if (!my_requisites)
throw something;
}
}
int main()
{
derived d;
d.method();
return 0;
}
In that case, where I'm not using pointers or references, but directly instances of the derived type, does the compiler need to do a run-time query against the vtable to select the correct override of requisites
(the one of derived
)? Or is that kind of behaviour as efficent as using no virtual functions? In other words, does the compiler know in compilation time that we are using derived::requisites()
?
Upvotes: 2
Views: 92
Reputation: 13073
vtable is not necessarily slower.
For example on x86 in a unix shared object, position independent code has been produced (gcc3, gcc4) using a hack to load ebx with the current eip. This value was used to find a jump table for any static functions. Calling a dynamic function could be performed by querying the this
pointer directly, and was faster (if no static functions were called in a given function).
The compiler does know the concrete type, and is able to call directly the function, but may choose to find the function virtually because :-
a) it may be faster.
b) it simplifies the amount of code generation cases.
Upvotes: 1