问题
Possible Duplicate:
gcc c++ virtual inheritance problem
Hi All, I am reading Effective C++ by scott myers books. It was mentioned about virtual base class and virtual inheritance as follows.
The rules governing the initialization of virtual base classes are more complicated and less intuitive than are those for non-virtual bases. The responsobility for initializing a virtual base is borne by the most derived class in the hierarchy. When a new derived class is added to the hierarchy, it must assume initialization responsiblities for its virtual bases (both direct and indirect)
Question is in above statement what are the rules for initialization of virtual base calsses and what are the responsiblities that derivied class has to take as mentioned in above text. Kindly request to explain with example.
Thanks!
回答1:
Let me explain the quotation by an example. Suppose, you've these classes,
struct A { A(int x) {} };
struct B : virtual A { B(int x) : A(x) {} };
struct C : virtual A { C(int x) : A(x) {} };
Note: A
is virtual base!
Now you define D
deriving from B
and C
:
struct D : B, C
{
//correct constructor - because A(x) is "present" in the initialization-list
D(int x) : A(x), B(x), C(x) { }
//wrong constructor - because A(x) is "absent" from the initialization-list!
//D(int x) :B(x), C(x) { }
};
Please note that D
is the most derived class in the hierarchy, so the responsibility of initializing A
is with D
, that is why D
explicitly writes A(x)
in it's constructor initialization-list (see above). If you write only B(x)
and C(x)
, then it would NOT even compile. See this: http://www.ideone.com/sO6m5
But once you write A(x)
, it compiles fine. See this: http://www.ideone.com/kiwh0
Now read the quotation again, and pay attention to the bold text:
The rules governing the initialization of virtual base classes are more complicated and less intuitive than are those for non-virtual bases. The responsobility for initializing a virtual base is borne by the most derived class in the hierarchy. When a new derived class is added to the hierarchy, it must assume initialization responsiblities for its virtual bases (both direct and indirect)
I hope this explanation helps you understanding the concept!
来源:https://stackoverflow.com/questions/4907264/about-virtual-base-class-and-virtual-inheritance-in-c