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?
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.
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.
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.
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.
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With