BSalunke
BSalunke

Reputation: 11737

Why the size of class is 1 byte contaning union members?

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?

Upvotes: 2

Views: 140

Answers (4)

john
john

Reputation: 88007

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

Upvotes: 7

Dinesh
Dinesh

Reputation: 939

@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

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129494

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.

Upvotes: 1

ibrahim demir
ibrahim demir

Reputation: 461

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..

Upvotes: 0

Related Questions