user1360764
user1360764

Reputation:

Why the size of the object is zero

I am getting the sizeof of object as zero, which is ought not to be. Please explain me the concept as why the compiler is giving this answer?

  #include<iostream>
  using namespace std;

  class xxx{
      public: int a[];  // Why this line is not giving error.
  }; 

  int main(int argc, char *argv[])
  {
      xxx x1;
      cout<<sizeof(x1); //Q=Why this code is not giving error.
      return 0;
  }

Upvotes: 4

Views: 299

Answers (4)

David Hammen
David Hammen

Reputation: 33116

That element a in your class xxx is called a flexible array member.

Flexible array members are not in the C++ standard. They are a part of C99. However, many compiler vendors provide flexible array members as a C++ extension.

Your code as-is is not legal C code. It uses C++ specific constructs. Your code is easy to change to C. Change the class to struct, get rid of the public, and change the use of C++ I/O to C's printf. With those changes, your converted code is still illegal C99 code. Flexible array members are only allowed as the last element of a structure that is otherwise non-empty.

Apparently your vendor took the flexible array member concept over to C++, but not the constraint that the structure be otherwise non-empty.

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

As the others have said, an object in C++ can never have size 0.

However, since the code isn’t valid C++ in the first place (arrays cannot be empty) this is inconsequential. The compiler just does what it wants.

GCC with -pedantic rejects this code. MSVC at least warns. My version of clang++ with -pedantic ICEs but does emit a warning before that.

Upvotes: 4

Luchian Grigore
Luchian Grigore

Reputation: 258598

You're not using a standard-compliant compiler. An object size can't be 0, even an empty class or struct has size 1. Moreover, the array dimension has to be specified.

EDIT: It's strange, ideone also prints out 0. In MSVS I get a warning, but at least the size is 1.

5.3.3. Sizeof

  1. [...] When applied to a class, the result is the number of bytes in an object of that class [...] The size of a most derived class shall be greater than zero. [...] The result of applying sizeof to a base class subobject is the size of the base class type. [...]

EDIT 2:

I tried the following in MSVS:

xxx a[100];

and it fails to compile. Strange how it doesn't pick up the error beforehand.

Upvotes: 2

Sachin Mhetre
Sachin Mhetre

Reputation: 4543

The size of an object can not be zero. even if the class is empty, its size is never zero.

Checkout the link to know more Bjarne Stroustrup's C++ Style and Technique FAQ.

Upvotes: 1

Related Questions