When can an empty class be useful?

A class containing no data members and no member functions is an empty class. It’s defined like this:

 class PlaceHolder {}; 

What’s it good for? It can serve as a place-holder for a yet-to-be defined class. For instance, it can be used as an interface class serving as a base for other classes; instead of waiting for it’s full implementation to be completed, it can be used this way in the interim. An empty class can also be used as a means of forcing derivation relationship among classes which are not originally descended from one base class. This is called a bottom-up design. Finally, it can be used to create a type for a dummy argument to distinguish between overloaded version of a function. In fact, operator new is overloaded exactly like that:

 #include using namespace std;void main(){try {int *p = new int[100]; //standard exception-throwing version of new }catch(bad_alloc & new_failure) {/*..*/}int *p = new (nothrow) int [100]; //standard exception-free version of new; returns NULL if failsif (p) {/*..*/}}

The nothrow arguments is of type nothrow_t, which is an empty class by itself.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: