Consider the example:
#include <iostream>
class A {
public:
virtual void f();
};
void A::f()
{
std::cout << "f() from A\n";
}
class B: public A {
public:
virtual void f() = 0;
};
class C: public B {
public:
void f();
};
void C::f()
{
std::cout << "f() from C\n";
}
int main()
{
C o;
o.f();
}
A::f()
implementation is "hidden" from class C, which provides its own implementation for f()
- effectively making A::f()
more or less pointless. I see little value in such class hierarchy design, but my question whether this is a valid C++ or just "works" (such as undefined behaviours)?
It is legal to have all member functions of a class be pure virtual functions. If the override specifier is added to the end of a member function declaration, what happens if the function is not specified as virtual in the parent class? There is a compiler error.
A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract. Classes having virtual functions are not abstract. Base class containing pure virtual function becomes abstract.
Can Virtual Functions be Private in C++? A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class.
Yes, Its correct that a Derived class has to OVERRIDE the function which is Pure Virtual in the Parent Class.
It is clearly allowed and supported by the standard (cf, for example, this online C++ standard draft), and thus clearly not undefined behaviour:
10.4 Abstract classes
5 [ 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 effect is that your class B
becomes abstract and any subclass - if it shall not be abstract, too - must define f()
then; the implementation in class A
can still be invoked through A::f()
, such that it is - from the perspective of reusing the implementation - not pointless.
This will safely achieve the goal of requiring the author of C
to provide an implementation for f()
.
I would query why this is needed — if the base implementation is not "valid" in your design then why does it exist, and/or why is it virtual
?
They can still invoke A::f()
, anyway, so whether this can be deemed "hiding" is open to debate.
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