Search code examples
c++inheritancevirtualfinalvirtual-inheritance

Is declaring a class in C++ as "final : public virtual" EVER useful?


When declaring a c++ class as final, is it ever needed to inherit base classes using virtual inheritance? I know what virtual inheritance is for and use it to avoid member duplication.

As an example, if I have these class definitions (imagine all of them having some members and virtual deconstructors)

class B : public virtual A {};
class C : public virtual A {};
class D : public virtual C {};

Does it make sense to define a next class as

class E final : public virtual D {}

or

class F final : public virtual B, public virtual C {};

or is the default inheritance, i.e.

class E final : public D {}
class F final : public B, public C {};

always enough?

This has bothered me for a long time now, as I see from time to time code, that includes

"final : public virtual"

Could the virtual be safely omitted here in any case?

Any hints/explanations are greatly appreciated


Solution

  • struct A { void foo() { cout << "foo" << endl; } };
    struct B : virtual A {};
    struct D final : virtual A, B {};
    
    D d;
    d.foo();
    

    Without virtual before A call to foo would be ambiguous.