devxlogo

When can an empty class be useful?

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist