Output of program

Light Poster
30Sep2005,15:27   #1
SATYAN JANA's Avatar
Code: CPP
/******************************/
class A
{
private:
  int a;
  char b;
};

class B
{
private:
  char b;
};

int main()
{
  A a;
  B b;
  cout<<sizeof(a)<<"  "<<sizeof(b)<<endl;
  return 0;
}
/******************************************/
What will be the output of the above program?
The output will be,-
8 1
Why?...
















In class B, 1 byte is as usual allocated for char 'b'. But in case of class A,
4 bytes for integer 'a' and next 4 bytes for char 'b'. This is because of packaging format.
Go4Expert Founder
30Sep2005,21:17   #2
shabbir's Avatar
I didn't knew this. Its really kool so out of excitement I tried even the double one and it gave 16 and 1
Light Poster
1Oct2005,10:31   #3
SATYAN JANA's Avatar
Hmmm,
even the size of pointers can change. If you have double and char* still it will be (8 + 8 =)16.
Go4Expert Founder
1Oct2005,14:13   #4
shabbir's Avatar
Quote:
Originally Posted by SATYAN JANA
Hmmm,
even the size of pointers can change. If you have double and char* still it will be (8 + 8 =)16.
Yup, seen that.
Newbie Member
15Oct2005,21:01   #5
rahul_scss's Avatar
Can somebody please tell me what exactly the rules of this packaging format are???
Go4Expert Founder
17Oct2005,14:50   #6
shabbir's Avatar
Quote:
Originally Posted by rahul_scss
Can somebody please tell me what exactly the rules of this packaging format are???
If you visualize the memory as rows and columns then if you need to allocate some memory in different rows[for different variables] then you have to allocate n no of cols of bytes for each variable and n is choosen as maximum size.

e.g.
Variable 1 mem [8 bytes] | | | | | | | |
Variable 2 mem [4 bytes] | | | |

Instead of 4 bytes it allocates 8 to keep the packaging format in good shape for second variable memory.

If you go about by sequential memory segment then also allocating each variable memory of n [choosen as maximum] is easier and so it allocates 8 + 8 bytes instead of 8 + 4 bytes.

Last edited by shabbir; 17Oct2005 at 14:54..
Newbie Member
17Oct2005,23:08   #7
rahul_scss's Avatar
Thanks Very Much Shabbir...
Go4Expert Founder
18Oct2005,10:36   #8
shabbir's Avatar
Quote:
Originally Posted by rahul_scss
Thanks Very Much Shabbir...
My pleasure.
Team Leader
18Oct2005,11:25   #9
pradeep's Avatar
Very useful piece of information Shabbir bhai.