Bramsh
Bramsh

Reputation: 389

creating an array without declaring its size, in a class c++

When I create an array without declaring its size in class, it doesn't give any error it works fine but why? this happens only inside the class, when I do same in my main function it gives error.

class B {
private:
     char array[]; 
public:
    ///.....///
};

Upvotes: 2

Views: 970

Answers (3)

Cubbi
Cubbi

Reputation: 47408

It appears that your compiler implements flexible array members (a C language feature) as an extension to C++.

Compiling your program with standard compliance enabled, produces these diagnostics:

clang:

main.cpp:3:11: error: flexible array member 'array' in otherwise empty class is a GNU extension [-Werror,-Wgnu-empty-struct]
     char array[]; 
          ^
main.cpp:3:11: error: flexible array members are a C99 feature [-Werror,-Wc99-extensions]

gcc:

test.cc:3:17: error: ISO C++ forbids zero-size array 'array' [-pedantic]

IBM:

"test.cc", line 3.11: 1540-2887 (S) A flexible array member is not permitted in this scope.

Oracle:

"test.cc", line 3: Error: In this declaration "array" is of an incomplete type "char[]".

PS: note that the way you're using it would be an error in C as well: you need at least one named member before the flexible

Upvotes: 7

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

First, an array with an empty size is non-standard. That same code will not compile with an ANSI C++ conforming compiler.

What you are probably using is a compiler with this extension of allowing empty array declarations (probably gcc / g++). Turn off the extensions, and you will get a compiler error.

To get around this issue, use a container such as std::vector.

Upvotes: 0

Victor
Victor

Reputation: 14573

If it is not a requirement of your program, then I suggest using a std::vector because of its "flexibility" and performance. You will not have to worry about the question you've just asked here:

class B
{
private:
    std::vector<char> array;
public:
    ///......///
}

Upvotes: 0

Related Questions