[ACCEPTED]-Can't C++ POD type have any constructor?-c++
POD
means Plain Old Data type which by definition 29 cannot have user-defined constructor.
POD 28 is actually an aggregate type (see the next 27 quotation). So what is aggregate? The C++ Standard 26 says in section §8.5.1/1,
An aggregate is 25 an array or a class (clause 9) with no user-declared constructors (12.1), no 24 private or protected nonstatic data members (clause 23 11), no base classes (clause 10), and 22 no virtual functions (10.3).
And section 21 §9/4 from the C++ Standard says,
[....] A 20 POD-struct is an aggregate class that has no non-static data members 19 of type non-POD-struct, non-POD-union 18 (or array of such types) or reference, and 17 has no user-defined copy assignment operator and no user-defined destructor. Similarly, a POD-union is an 16 aggregate union that has no non-static 15 data members of type non-POD-struct, non-POD-union 14 (or array of such types) or reference, and has 13 no user-defined copy assignment operator and no user-defined destructor. A POD class is a class that is 12 either a POD-struct or a POD-union.
From 11 this, its also clear that POD class/struct/union 10 though cannot have user-defined assignment operator and user-defined destructor also.
There are 9 however other types of POD. The section 8 §3.9/10 says,
Arithmetic types (3.9.1), enumeration 7 types, pointer types, and pointer to member 6 types (3.9.2), and cv-qualified versions 5 of these types (3.9.3) are collectively 4 called scalar types. Scalar types, POD-struct 3 types, POD-union types (clause 9), arrays 2 of such types and cv-qualified versions of 1 these types (3.9.3) are collectively called POD types.
Read this FAQ : What is a "POD type"?
The class A is POD and can be initialized 13 like this
Sorry, that is wrong. Because b
is 12 private, the class is not a POD.
But Clang 11 assumes A as non-aggregate type. Why I can't 10 have constructor like that? Or should I 9 do something else?
This is a limitation of 8 C++ as it exists currently. C++0x will not 7 have this limitation anymore. While in C++0x 6 your type is not a POD either, your initialization 5 will work (assuming that you make that constructor 4 public
).
(Also, I think a better term for you to 3 use here is "aggregate". The requirement 2 for using { ... }
is that your class is an aggregate. It 1 doesn't have to be a POD).
The other answers describe the POD rules 5 pretty well. If you want to get a similar 4 initialization style to a constructor for 3 a POD you can use a make_
-style function, for 2 example:
struct A
{
int i_;
};
A make_A(int i = 0)
{
A a = { i };
return a;
}
now you can get initialized POD 1 instances like:
A a = make_A();
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.