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?
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?
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.
Isn't Foo just a waste of space
Indeed it is; you can't instantiate it since it's abstract, and you can't override the function to make a non-abstract derived class.
It could be used as a way of preventing a class from being instantiated, if you want to do that for some reason; but even then it would probably make more sense to delete the default constructor.
and an accident in the making?
Not really. Since you can't do anything with the class, you can't do anything wrong with it.
If I'm reading the grammar in 9.2 correctly this is actually legal although I may have missed something in the notes prohibiting it.
member-declarator: declarator virt-specifier-seq(opt) pure-specifier(opt)
Then it shows that virt-specifier-seq
can be final
and pure-specifier
is = 0
I can't see any way this would be useful although there may be some corner case that makes use of it.
© 2022 - 2024 — McMap. All rights reserved.
dynamic_cast
you need a vptr andfoo()
ensures that. – Overripedynamic_cast
. You can't create an object because the class is abstract. So I ask again - dynamic cast between what and what? – Dannadanneldynamic_cast
requires an object, and neither this class nor any class derived from it can be instantiated. – Woodpecker