Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

c++ - Multiple (diamond) inheritance compiles without "virtual", but doesn't with

Given the following code (without virtual inheritance) :

class A
{
public:
    virtual void f() = 0;
};

class B : public A
{
 public:
    virtual void f() {}
};

class C : public A
{
 public:
    virtual void f() {}
};

class D : public B, public C
{

/* some code */
};


int main()
{
    D d;
    return 0;
}

the code compile.

On the other hand , here :

class A
{
public:
    virtual void f() = 0;
};

class B : virtual public A
{
    virtual void f() {}
};

class C : virtual public A
{
    virtual void f() {}
};

class D : public B, public C
{
    /* some code */
};


int main()
{
    D d;
    return 0;
}

The compiler presents a compilation error:

no unique final overrider for 'virtual void A::f()' in 'D' . 

Why is it different in the second code ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your first scenario hierarchy corresponds to:

    F()   F()
     A     A
     |     |
 F() B     C F()
         /
        D 

Where D is not abstract, because there are two A subobjects in an object of type D: One that is made concrete by B through the lattice of B, and another that is made concrete through the lattice of C.

Unless you try to invoke the function F() on object of D there will not be any ambiguity.

Your second scenario hierarchy corresponds to:

       F()  
        A
      /   
 F() B     C F()
         /
        D  

In this scenario, the object D has a single Base class A sub object, and it must override and provide implementation of the pure virtual function in that subobject.


Herb Sutter's articles in Guru Of The Week(GOTW) are a nice read for Multiple Inheritance:

  1. Multiple Inheritance Part I
  2. Multiple Inheritance Part II
  3. Multiple Inheritance Part III

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...