c++ - When virtual functions are invoked statically? -
what performance difference between calling virtual function derived class pointer directly vs base class pointer same derived class?
in derived pointer case, call statically bound, or dynamically bound? think it'll dynamically bound because there's no guarantee derived pointer isn't pointing further derived class. situation change if have derived class directly value (not through pointer or reference)? 3 cases:
- base pointer derived
- derived pointer derived
- derived value
i'm concerned performance because code run on microcontroller.
demonstrating code
struct base { // virtual destructor left out brevity virtual void method() = 0; }; struct derived : public base { // implementation here void method() { } } // ... in source file // call virtual method base class pointer, guaranteed vtable lookup base* base = new derived; base->method(); // call virtual method derived class pointer, difference? derived* derived = new derived; derived->method(); // call virtual method derived class value derived derivedvalue; derived.method();
in theory, c++ syntax makes difference member function call uses qualified member name. in terms of class definitions be
derived->derived::method();
this call ignores dynamic type of object , goes directly
derived::method()
, i.e. it's bound statically. possible calling methods declared in class or in 1 of ancestor classes.everything else regular virtual function call, resolved in accordance dynamic type of object used in call, i.e. bound dynamically.
in practice, compilers strive optimize code , replace dynamically-bound calls statically-bound calls in contexts dynamic type of object known @ compile time. example
derived derivedvalue; derivedvalue.method();
will typically produce statically-bound call in virtually every modern compiler, though language specification not provide special treatment situation.
also, virtual method calls made directly constructors , destructors typically compiled statically-bound calls.
of course, smart compiler might able bind call statically in greater variety of contexts. example, both
base* base = new derived; base->method();
and
derived* derived = new derived; derived->method();
can seen compiler trivial situations allow statically-bound calls.
Comments
Post a Comment