Featured post
c++ - Which function to call? (delegate to a sister class) -
i read in c++ faq lite
[25.10] mean "delegate sister class" via virtual inheritance?
class base { public: virtual void foo() = 0; virtual void bar() = 0; }; class der1 : public virtual base { public: virtual void foo(); }; void der1::foo() { bar(); } class der2 : public virtual base { public: virtual void bar(); }; class join : public der1, public der2 { public: ... }; int main() { join* p1 = new join(); der1* p2 = p1; base* p3 = p1; p1->foo(); p2->foo(); p3->foo(); }
"believe or not, when der1::foo() calls this->bar(), ends calling der2::bar(). yes, that's right: class der1 knows nothing supply override of virtual function invoked der1::foo(). "cross delegation" can powerful technique customizing behavior of polymorphic classes. "
my question is:
what happening behind scene.
if add der3 (virtual inherited base), happen? (i dont have compiler here, couldn't test right now.)
what happening behind scene.
the simple explanation that, because inheritance base
virtual in both der1
, der2
, there single instance of object in derived object join
. @ compile time, , assuming (which common case) virtual tables dispatch mechanism, when compiling der1::foo
redirect call bar()
through vtable.
now question how compiler generates vtables each of objects, vtable base
contain 2 null pointers, vtable der1
contain der1::foo
, null pointer , vtable der2
contain null pointer , der2::bar
[*]
now, because of virtual inheritance in previous level, when compiler processes join
create single base
object, , single vtable base
subojbect of join
. merges vtables of der1
, der2
, produces vtable contains pointers der1::foo
, der2::bar
.
so code in der1::foo
dispatch through join
's vtable final overrider, in case in different branch of virtual inheritance hierarchy.
if add der3
class, , class defines either of virtual functions, compiler not able cleanly merge 3 vtables , complain, error relating ambiguity of multiply defined method (none of overriders can considered final overrider). if add same method join
, ambiguity no longer problem, final overrider member function defined in join
, compiler able generate virtual table.
[*] compilers not write null pointers here, rather pointer generic function print error message , terminate
application, allowing better diagnostics plain segmentation fault.
- Get link
- X
- Other Apps
Comments
Post a Comment