Is it valid to override virtual function with pure specifier? [duplicate]
Asked Answered
K

1

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?

Kerley answered 5/3, 2020 at 10:43 Comment(7)
Maybe, you can add the tag [language-lawyer] since it's about language specification ?Anthurium
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?Cavan
@MartinMorterol Added, thanks!Kerley
@Cavan 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).Kerley
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 #46447152Levirate
Dup of Can I override a virtual function with a pure virtual one? and Turning a non-pure virtual function into pure in a subclass etc.Banneret
Huh, I can close my own question by voting to close and then agreeing with that vote, interesting... Thanks for the links @LanguageLawyerKerley
R
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.

Risa answered 5/3, 2020 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.