2

I'm working on C++: Following is the code snippet:

class my
{
  union o
  {
    int i;
    unsigned int j;
  };

  union f
  {
    int a;
    unsigned int b;
  };
};

I found the size of class "my" is 1 byte. I don't understood why the value is 1 byte? Can any one explain me this result?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
BSalunke
  • 11,499
  • 8
  • 34
  • 68
  • 1
    Might be this will explain you the reason.. http://stackoverflow.com/questions/621616/c-what-is-the-size-of-an-object-of-an-empty-class – Dinesh Nov 15 '13 at 08:06
  • What compiler are you using? – Prasanna Aarthi Nov 15 '13 at 08:07
  • @RichieHindle Or is it? – UldisK Nov 15 '13 at 08:08
  • @UldisK Does the OP consider it to be empty? – john Nov 15 '13 at 08:08
  • @john Well, there are no members in class my, so it is empty. Type definitions of o and f are hidden within class namespace but they are not members. – UldisK Nov 15 '13 at 08:10
  • @UldisK I know it's empty but to answer the question it would help to know if the OP think's it's empty. It could be that the OP thinks they've written a class with two anonymous unions, for instance. – john Nov 15 '13 at 08:13

4 Answers4

7

Your class is empty, it's contains two union type declarations but no data members. It's usual for empty classes to have a non-zero size, as explained here

Community
  • 1
  • 1
john
  • 85,011
  • 4
  • 57
  • 81
1

You will find that my::o and my::f have a size appropriate for their content (typically 4 bytes). But since neither my::f or my::o are actually part of your class as such, just declared in the class, they are not taking up space within the class.

A similar example would be:

class other { typedef char mytype[1024]; };

now, other::mytype would be 1024 bytes long, but other would still not contain a member of mytype.

Tadeusz A. Kadłubowski
  • 8,047
  • 1
  • 30
  • 37
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

A union is a user-defined data or class type that, at any given time, contains only one object from its list of members. So dont expect from class to allocate 8 bytes to each unions.

You have also defined union types but you didnt initiate/alloc a space for it. Since class is defined allready it has no-zero size, it is 1 byte to check if class is defined or not..

ibrahim demir
  • 421
  • 3
  • 16
0

@RithchiHindle the answer still exists in the same link..

Although you have 2 unions inside your code still that is not allocated yet.. even after you have created an object of the same class and check the size than you will get the size as 1 again as memory has been not initialized for same.. if you have created an instance of your union than you will get the 8 bytes as size

Dinesh
  • 929
  • 7
  • 25