Re: same overhead in calling virtual and non virtual member function...?
Dnia Fri, 08 Sep 2006 19:21:25 -0400, ypjofficial napisa(a):
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]();
This is right.
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?
Compilers use class declaration. When a method is virtual it is clearly
stated in the code of a class or its base classes. (With the 'virtual'
keyword.) When a method is not virtual, the compiler uses method from the
class the pointer has type of. (See example)
Therefore, have no worries, non virtual methods are never called using
VTable. In fact, even virtual methods may not use it (i'm not sure
about wording The Standard puts here, but imho it may not be necessary).
VTable must be used when you call some virtual method using a pointer or a
reference to the class.
struct Base; {
virtual void v_method();
void method();
};
struct Derived : public Base {
virtual void v_method();
void method();
};
Base b;
Derived d;
Base* pb = &d;
b.v_method(); // not here
d.v_method(); // not here
pb->v_method(); // here
pb->method(); // calls Base::method()
That example does something one should not do. It overrides nonvirtual
method, what is not forbidden by the standard, but is a bad practise as it
misleads users of your class.
Regards,
--
Tomek 'QsoRiX' Rydzyski Linux Registered User #178082
http://rtfm.killfile.pl/ http://apcoln.linuxpl.org/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]