Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 736
Yksisarvinen Avatar asked Mar 05 '20 10:03

Yksisarvinen


People also ask

Can you override a pure virtual function?

A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax.

Can we override virtual method in C++?

Virtual, final and override in C++ C++11 added two keywords that allow to better express your intentions with what you want to do with virtual functions: override and final . They allow to express your intentions both to fellow humans reading your code as well as to the compiler.

Is it mandatory to override virtual function in derived class True or false?

It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. A class may have virtual destructor but it cannot have a virtual constructor.

Can pure virtual function be protected?

However, with pure virtuals, there is no base implementation... So isn't it functionally equivalent to declare a pure virtual as either private or protected? A protected pure virtual doesn't make sense because you can't ever invoke the base class's corresponding method.


1 Answers

[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.

like image 137
Daniel Langr Avatar answered Oct 17 '22 15:10

Daniel Langr