c++ - Virtual function mechanism -
here code:
#include <iostream> using namespace std; class t { public: virtual int f(int x) { cout << "t::f" << endl; homecoming 0; } void g() { f(1); cout << "t::g" << endl; } virtual void h() { g(); cout << "t::h" << endl; } }; class s: public t { public: int f(double y) { cout << "s::f" << endl; homecoming 2; } virtual void g() { f(1); cout << "s::g" << endl; } virtual void h() { g(); cout << "s::h" << endl; } }; int main() { t t; s s; t * p = &s; p -> f(1.5); p -> g(); p -> h(); homecoming 0; } i confused functions executed, though have read virtual function mechanism in several textbooks. help highly appreciated.
update: have run code , output is:
t::f t::f t::g s::f s::g s::h i can't understand how take functions executed when within of function, instance.
in class t silently created pointer virtual table of functions (you can find exists if phone call sizeof(t), bigger @ sizeof(void*) have to). class s have such pointer virtual table.
such virtual table have pointers functions.
when class s created, makes re-create of virtual table t. , replace pointers functions defined @ t pointers functions defined s. so, not replace pointer function f(), because don't define in s, replace pointer function h(), because redefined in s.
so, when object virtual table when first pointer points t::f(), , sec points s::h(). , seek operate object object t.
so, when phone call f() - receive if t::f() called. when phone call h() - receive if s::h() called.
method without "virtual" don't inputs table. so, t* know virtual method added in kid class, , t* phone call it's own virtual method if not redefined in object.
that all.
c++ oop virtual-functions
No comments:
Post a Comment