Re: Virtual function calls at compile time
space.ship.traveller@gmail.com wrote:
Hello. I have a question regarding the performance cost of virtual
function call
The cost is around zero, unless you can prove with a profiler that it
isn't. ;)
class _Traits {
public:
virtual int & value () = 0;
void multiply () {
value() = value() * 2;
}
};
Just one comment here: identifiers beginning with an underscore and a
capital letter are reserved and you should not use them. In any case, if
you want to somehow separate your code from other code use a namespace
instead. E.g. Boost uses the namespace 'detail' to put things that must be
visible to the compiler but should be ignored by the user (IOW for
implementation details).
class Number : public _Traits {
public:
int k;
Number(int n) : k(n) {}
int & value () {
return k;
}
};
void funcA(Number a) {
// This can be optimised right? - it won't be a virtual lookup?
a.multiply();
}
This is implementation-defined. However, since 'a' is passed by value, the
compiler knows the static and dynamic type of it without further context.
Since the called function depends on the dynamic type, it can avoid lookup
at runtime.
void funcB(Number &a) {
// How about here?
a.multiply();
}
void funcC(Number *a) {
// And here?
a->multiply();
}
In both cases the compiler only knows the static type, the dynamic type
could be anything that is derived from class 'Number', so it has to do the
lookup at runtime.
int main (int argc, char ** argv) {
Number n(5);
funcA(n);
funcB(n);
funcC(&n);
}
Note: some compilers are smart enough to figure out that the functions are
not called with anything but a 'Number' and thus optimise the lookup away.
Some are even smart enough to do that when things are scattered to several
sourcefiles.
cheers
Uli
--
Sator Laser GmbH
Gesch?ftsf?hrer: Michael W?hrmann, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]