Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top