Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pure virtual final functions : legal in C++11

Tags:

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?

like image 315
aiao Avatar asked Dec 14 '12 14:12

aiao


People also ask

Do pure virtual functions have to be implemented?

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.

Do pure virtual functions have to be overridden?

¶ Δ 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.

What is the point of a pure virtual function?

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.

Can pure virtual functions be private?

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.


1 Answers

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.

like image 116
Damon Avatar answered Oct 09 '22 04:10

Damon