18

Note: I do not ask whether or not this is reasonable thing to do or if this is good design. I'm just asking if this is well-defined behaviour and if the results are as expected.

I came upon a following class hierarchy:

struct A
{
    virtual void foo() = 0;
};

struct B: public A
{
    void foo() override 
    {
        std::cout << "B::foo()\n";
    }
};

struct C: public B
{
    virtual void foo() = 0;
};

struct D: public C
{
    void foo() override
    {
        std::cout << "D::foo()\n";
    }
};

int main()
{
    A* d = new D;
    d->foo(); //outputs "D::foo()"
    // A* c = new C; // doesn't compile as expected
}

Is this code well defined? Are we allowed to override definition with pure-specifier?

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • Maybe, you can add the tag [language-lawyer] since it's about language specification ? – Martin Morterol Mar 05 '20 at 10:49
  • I guess you cannot instantiate `C` if it's abstract. On the other hand, I would say overwriting and overwriten function is not a good practice, in which case would you use this? – Ivan Mar 05 '20 at 10:49
  • @MartinMorterol Added, thanks! – Yksisarvinen Mar 05 '20 at 10:54
  • @Ivan I'm afraid it already exists in our code, it got past our code review unfortunately. I just wonder if this is okay thing to do (and what it actually is doing). – Yksisarvinen Mar 05 '20 at 10:55
  • I was wondering in this question if it is actually valid to `override` pure virtual functions like it is done here in `struct B` and found that this seems indeed good practice - see https://stackoverflow.com/questions/46446652/is-there-any-point-in-using-override-when-overriding-a-pure-virtual-function/46448798 – Odysseus Mar 05 '20 at 13:14
  • 2
    Dup of [Can I override a virtual function with a pure virtual one?](https://stackoverflow.com/questions/33526666/can-i-override-a-virtual-function-with-a-pure-virtual-one) and [Turning a non-pure virtual function into pure in a subclass](https://stackoverflow.com/questions/16585033/turning-a-non-pure-virtual-function-into-pure-in-a-subclass) etc. – Language Lawyer Mar 06 '20 at 00:48
  • Huh, I can close my own question by voting to close and then agreeing with that vote, interesting... Thanks for the links @LanguageLawyer – Yksisarvinen Mar 06 '20 at 15:56

1 Answers1

18

[class.abstract/5] of the current draft Standard:

[Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function may override a virtual function which is not pure. — end note]

The very same note is included even in the C++11 Standard. So, the answer is yes, it is valid.

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93