Salman,
Your question is really interesting and many C++ programmers never
notice this point. This is all due the way memory is allocated
internally for class members. I'm trying to put something for you
below that will help you get what exactly is the story behind this:
1) We know that a "char" takes 1 byte in memory.
2) Memory internally organised in chunks of bytes and depending on
this chunk size we determine what is the word size of the computer.
You might have heard of 16-bit, 32-bit, 64-bit computer.
3) It means when memory being allocated, it is tried to first allocate
the memory from one word as far as possible. That's the reason when
you put 2 chars in a sequence it is allocated 2 consecutive bytes of
the same "word". Note here that if you're using 32-bit computer - word
size is 4 bytes - it means even if you add 2 more char members
consecutively they will occupy only 4 bytes. But as you allocate 5th
char it needs another word (i.e. next 4 bytes).
4) When you declare int *c, it requires 4 bytes while 2 bytes already
allocated to chars a and b, it means not enough space to accomodate
complete int* so it will look for next word i.e. next 4 bytes.
5) This way char a, char b occuply first word (4 bytes). Note that
only 2 bytes are in use. 2 are unused. int *c occupies next word (i.e.
4 bytes) so making a total of 8 bytes.
6) Now when you rearrange char a, int *c, char b. In this instance
char a uses first word, int *c uses second word, and char b uses third
word, i.e. a total of 12 bytes.
Hope it makes sense.
Cheers,
VCLover
Try this class declaration:
class A {
char a;
int* c;
char b;
int* f;
char d;
char e;
};
Size of this class is 20 bytes on a 32-bit computer.
On Feb 21, 11:03 am, "Salman" <salman0...@gma il.comwrote:
I want to know abt the size of the class using sizeof function. i have
pasted 2 programs. Both gives different sizes of the class just by re-
arranging the order of the private varibles. Tell me whats the reason
behind it. Im pasting both the programs. I using VC++ 6
---------------Program 1 ----------------------------
#include <iostream>
using namespace std;
class A {
char a;
char b;
int* c;
};
int main(void) {
A a;
cout<<sizeof(a) ;
return 0;
}
---------------Program 2 ----------------------------
#include <iostream>
using namespace std;
class A {
char a;
int* c;
char b;
};
int main(void) {
A a;
cout<<sizeof(a) ;
return 0;
}- Hide quoted text -
- Show quoted text -