开发者

Virtual methods on a virtual base class

Something that has been confusing me about virtual base class inheritance... Given the following classes:

class A
{
  virtual void开发者_如何学Python foo() = 0;
}
class B : virtual A
{
  void foo() { /* do X */ }
}
class C : virtual A
{
  void foo() { /* do Y */ }
}
class D : B, C
{
}

Will this compile? If so, what would be the result of the following code:

D d;
A* a = &d;
a->foo();


It should not compile, the function foo will be ambiguous. Since A::foo() is pure virtual function, the ambiguity has to be resolved.


It won't compile. GCC:

error: no unique final overrider for ‘virtual void A::foo()’ in ‘D’

You could have found that out yourself pretty fast.

Same with icc:

error #361: override of virtual function "A::foo" is ambiguous


It won't compile for three reasons none of which has anything to do with virtual inheritance(well, maybe the last one).

  1. You forgot the semicolons after class definitions

  2. Your inheritance is private

  3. D::foo() is ambiguous when not overriden explicitly

By the way, the definition of D itself is ill-formed, not just the fact that you try to use it. I mean if your main() function were empty, it still wouldn't compile.

And "Will this compile?" has the obvious answer "Why don't you try?"

Quote from the standard: 10.3.10

The following example shows a function that does not have a unique final overrider:

 struct A {
 virtual void f();
 };
 struct VB1 : virtual A { // note virtual derivation
 void f();
 };
 struct VB2 : virtual A {
 void f();
 };
 struct Error : VB1, VB2 { // ill-formed
 };


No, it won't:

diamond.cpp:24:7: error: request for member ‘foo’ is ambiguous
diamond.cpp:13:8: error: candidates are: virtual void C::foo()
diamond.cpp:8:8: error:                 virtual void B::foo()

This is called the Diamond problem, see http://en.wikipedia.org/wiki/Diamond_problem

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜