c++ - How does virtual inheritance actually work? -
c++ - How does virtual inheritance actually work? -
i know diamond problem thing - when google "virtual inheritance" results mention only diamond problem. want know how works in general , how different normal inheritance.
i know when class (normally) inherits class contains members (fields , methods, leaving aside access levels). of them may overridden or hidden new members they're still there. inheritance defines relationships between classes in hierarchy affects casting , polymorphism.
now how virtual inheritance different? instance:
class { public: int a; int b; void fun(int x) {} void gun(int x) {} }; class b : public { public: int a; int c; void fun(int x) {} void hun(int x) {} }; class c : virtual public { public: int a; int c; void fun(int x) {} void hun(int x) {} };
what differences between b
, c
? there other differences illustration doesn't exploit? standard say? also, if there's difference between c++03 , c++11 please mention it.
with single level of inheritance, there's no difference in behaviour.
the difference when inheriting multiple base of operations classes, have mutual base of operations class:
struct {}; struct b : virtual {}; struct c : virtual {}; struct d : b,c {};
in example, virtual inheritance, d
contains 1 a
sub-object, b
, c
subobjects share; "diamond" pattern:
/ \ b c \ / d
without virtual inheritance, contain 2 a
sub-objects, , no "diamond":
a | | b c \ / d
with or without multiple inheritance, there's still difference if have more 1 level of inheritance: virtual base of operations class must initialised derived class, not immediate derived class. avoid ambiguity in case of multiple inheritance, (in illustration above) both b
, c
otherwise responsible initialising shared a
.
c++ inheritance virtual-inheritance
Comments
Post a Comment