class Foo { public: virtual int foo() final = 0; };
Compiles fine.
Isn't Foo
just a waste of space, and an accident in the making? Or am I missing something?
pure virtual methods do not have to be implemented in derived classes (foo() has no implementation in class C - compiler will compile) In C++ there are a lot of loopholes. It does not need to be implemented in ALL derived classes, but it MUST have an implementation in all derived classes that you intend to instantiate.
¶ Δ 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.
A pure virtual function makes it so the base class can not be instantiated, and the derived classes are forced to define these functions before they can be instantiated. This helps ensure the derived classes do not forget to redefine functions that the base class was expecting them to.
Answer 1: It's not allowed. A private function is not visible to derived classes and they cannot override it. It's not valid C++ because every pure virtual function must be overridden to instantiate the object.
It is almost a complete waste of space, as you've said. There is at least one admittedly contrieved usage for this. The fact that it compiles, by the way, is not surprising. As long as code is legitimate, it needs not "make sense" to compile.
Say you want to use Foo
as a policy. That means it will be used as a template parameter, but it needs not be instantiated. In fact, you really don't want anyone to ever instantiate the class (although admittedly I wouldn't know why, what can it hurt).
This is exactly what you have here. A class with a type that you can lay your hands on, but you can't instantiate it (though making the constructor private would probably be a lot more straightforward).
As an added bonus, you could add enum
s or static functions inside the class scope. Those could be used without actually instantiating, and they'd be within that class' namespace. So, you have a class that's primarily usable only as type, but you still have "some functionality" bundled with it in the form of static functions.
Most of the time, one would probably just wrap that stuff into a namespace, but who knows, in some situation, this might be the desired way.
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