Re: same overhead in calling virtual and non virtual member function...?
Greg Herlihy wrote:
ypjofficial@indiatimes.com wrote:
So far I have been reading that in case of a polymorphic class ( having
at least one virtual function in it), the virtual function call get
resolved at run time and during that the vtable pointer is made use
eg.
of..
class one
{
virtual void fun1(){ cout<<"one::fun1";} //This is a virtual
function.
void fun2(){ cout<<"one ::fun2";}//Not a virtual function.
};
so when the virtual function gets called through the base class poitner
the call actually gets expanded to the code like this
o->vfptr[0]();
Yes, at least for C++ compilers that use vtables to implement
virtual functions. But the general point is that one function
call to a virtual method in the source code can - at runtime -
execute any of several distinct methods (based on the runtime
type of the object) each and every time. So calling a virtual
method requires run-time decision-making which is not needed
when calling non-virtual methods or global functions.
My confusion is how the call to the non virtual function
(here fun2)gets resolved in polymorphic class? When does
the compiler decide to look into the vtable and when not to
look?
The compiler generates "lookup-code" when the method being called has
been declared virtual, otherwise it generates a direct call to the
method as determined by the object's static type.
More strictly speaking: if the compiler doesn't know at compile
time which function to call, it must generate code to determine
this at run-time. By definition, if the function isn't virtual,
the compiler does know this at run time. If the function is
virtual, it may or may not know it, depending on how good it is.
Almost all compilers will know it if the call is through an
actual object; if the call is through a reference or a pointer,
it depends on the quality of the optimizer.
--
James Kanze (Gabi Software) email: kanze.james@neuf.fr
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]