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
class _Traits {
public:
virtual int & value () = 0;
void multiply () {
value() = value() * 2;
}
};
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();
}
void funcB(Number &a) {
// How about here?
a.multiply();
}
void funcC(Number *a) {
// And here?
a->multiply();
}
int main (int argc, char ** argv) {
Number n(5);
funcA(n);
funcB(n);
funcC(&n);
}
The compiler can optimise this code, but I'm not sure if this is
reliable behaviour across compilers. The reason why this is important
is because I use this structure for implementing traits for specific
template classes:
Optimization is almost by definition something that cannot be relied
upon. Now to the actual details.
When you pass a polymorphic type by value the compiler is not only free
to statically bind calls to its member functions but usually will (it
would need a degree of perversity from the implementor to insist on a
virtual call. Actually I am not certain without going back to the
Standard whether making the call virtual is non-conforming in such a case)
When you pass to a pointer or reference parameter the compiler has, in
general, to use the virtual mechanism because the function has to
implement polymorphism. I wrote 'in general' because in the case that
the function gets implemented inline the compiler may be able to do
static binding. Note that even if you do not declare a function as
inline the implementation can place it inline and increasingly modern
implementations do so, often delaying the decision till link time.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]