I have this situation which I cannot explain why it compiles:
#include <iostream>
using namespace std;
class X {
public:
X() {cout << "in X constructor: " << endl;};
};
class Y {
public:
Y() {cout << "in Y constructor" << endl;};
private:
X x[];
};
int main() {
Y y;
return 0;
}
I am defining a variable size array of X
as a member of class Y
. Defining X
it is such a way outside the class would surely result in a compile error, but not within the class. What’s more, the constructor of X
is never called.
So what is happening here?
C99, 6.7.2.1/16 (n1256)
As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.
It is not a variable-length array. It isn't anything like a data member, more like an interface to tell the compiler you can access some memory via the name of the flexible array member.
/17
EXAMPLE After the declaration:
struct s { int n; double d[]; };
the structure
struct s
has a flexible array memberd
. A typical way to use this is:int m = /* some value */; struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));
and assuming that the call to
malloc
succeeds, the object pointed to byp
behaves, for most purposes, as ifp
had been declared as:struct { int n; double d[m]; } *p;
This is not allowed in C++11, but accepted by g++ and clang++ as an extension. As the number of elements isn't known to the constructor of the struct
(for C++), the constructor cannot initialize those elements (automatically).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With