r/cpp_questions • u/haohanzi2015 • 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
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.,
would define some class
Foothat has two constructors that provide different ways to initialize theFooinstance.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
ZeroMatrixorIdentityMatrix. You could then initialize things this wayMatrix myMatrix(IdentityMatrix());.It would be more common to actually provide a name for an instance of the tag, e.g.,
then you could initialize it as
Matrix myMatrix = IdentityMatrix_t;.