Written by on March 28, 2020 in C++, Programming with 0 Comments

In the previous post, we looked at the std::is_destructible<T> type trait. Today, let us try to understand another type trait std::is_empty<T>.

As per the specification, is_empty<T>::value will return true in the following cases:

– The class/struct has no non-static data member

– The class/struct does not define a virtual function

– The class/struct does not derive from a virtual base class

– The class/struct does not derive from non-empty base classes

Let us understand this concept by looking at some examples.

Here is our first example:



For convenience, we will use std::is_empty_v<T> instead of is_empty<T>::value. Also, just to make it a bit more interesting, I am printing the sizeof” each class. 

When we run this program, we get the following output:

Example1 Output

Example1 Output

The output is along the expected lines. You can see that even if a class is empty, its size is always greater than zero (the actual value is implementation dependent).  The reason why class E is not empty is because it has an instance variable (although the class A is empty).

Let us now look at some examples involving inheritance.

Inheritance Examples

Inheritance Examples

Here is the corresponding output:

Example2 Output

Example2 Output

The behaviors of classes A, B, C, and D are as expected. However, I am surprised by the output corresponding to class E. I think this should be true since, as per the spec, deriving non-virtually from empty classes makes the class empty. I believe this is a bug in Microsoft C++ compiler.

Here are some more examples involving inheritance:


Example: Virtual Derivation and Virtual Functions

These involve virtual functions and virtual derivation. What do we expect in these cases?

Example3 Output

Example3 Output

Again, there is no surprise here. If a class has a virtual function and/or derives virtually from another class, it is not an empty class as per the spec.

Before concluding, let us consider the case of a union and a class with bit field:

Example4: Union and Bit Field

Example4: Union and Bit Field

This is the output generated:

Example4 Output

Example4 Output

As expected, unions are non-empty. And, a class with a bit field of size zero is considered empty. 

I hope the above examples provide some clarity on the behavior of std::is_empty<T> type trait. 

For the examples, I used Microsoft Visual Studio 2019 (ver 16.4.5). You can download the examples from here.

Have a nice weekend! 

Tags: , ,


If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *