As we know, struct
and class
are interchangeable in many places in the language. Confusingly, the keywords themselves do not necessarily correspond to the language used in the standard. For example, in draft standard N4567 [class]/10,
A POD struct109 is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). A POD class is a class that is either a POD struct or a POD union.
In over-simplified terms, struct
and class
are interchangeable in the following cases:
- declaration of a "class"
- declaration of a scoped enumeration type
- elaborated type specifier unless the "class" was declared with
union
However, struct
explicitly cannot be used in a template declaration to introduce type template parameters:
template <struct T> // error
I'm unable to see any significant difference between struct
and class
, even in the POD example above because a POD struct as defined in the standard can be declared with either struct
or class
.
[class]/8 A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class. A standard-layout union is a standard-layout class defined with the class-key union.
This seems rather redundant and confusing while introducing a glaring inconsistency.
I have two questions:
Are there any technical differences that I have missed that significantly distinguish
struct
andclass
?What is the rationale, if any, behind this clumsiness?
I'm ignoring the difference between default access specifiers because everyone knows that already.
template<typename T>
, but nottypename T{};
? – eerorikatemplate < template<typename> class C >
, but nottemplate < template<typename> typename C >
– Revolver_Ocelotstruct T
with members and one which declared it as aclass T
with all public members, would both link correctly to an object file that implemented theT
and theT::...
members? – Rob Starling