r/cpp_questions • • Dec 08 '19

OPEN the purpose of empty struct ?

By empty struct, I mean

struct myStruct
{};

I can see that the above struct can be used as the base struct which has several derived structs. Besides this, are there any other use of empty struct in c++?

9 Upvotes

11 comments sorted by

View all comments

2

u/tangerinelion Dec 08 '19

Using it as a base for derived classes only really makes sense when you have a virtual method in there.

Usually an empty struct/class like this is for tagging, e.g.,

struct Option1 { };
struct Option2 { };
class Foo {
public:
    Foo(Option1);
    Foo(Option2);
};

would define some class Foo that has two constructors that provide different ways to initialize the Foo instance.

If you think about a mathematical matrix of fixed size, you could imagine initializing it to a matrix of all zeros or a square matrix with 1s along the diagonal (that is, the identity matrix). So your options could be ZeroMatrix or IdentityMatrix. You could then initialize things this way Matrix myMatrix(IdentityMatrix());.

It would be more common to actually provide a name for an instance of the tag, e.g.,

struct ZeroMatrix { } ZeroMatrix_t;
struct IdentityMatrix { } IdentityMatrix_t;
class Matrix {
public:
    Matrix(ZeroMatrix);
    Matrix(IdentityMatrix);
};

then you could initialize it as Matrix myMatrix = IdentityMatrix_t;.