473,569 Members | 2,652 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Size of a class

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;
}

Feb 21 '07 #1
6 2151
Salman wrote:
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
>
class A {

char a;
char b;
int* c;

};
versus
class A {

char a;
int* c;
char b;
};

The compiler is free to introduce any padding necessary for alignment
purposes. My guess is that you are seeing 8 for the first and 12 for
the second.
Feb 21 '07 #2
Salman <sa********@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 ----------------------------
class A {

char a;
char b;
int* c;

};

---------------Program 2 ----------------------------
class A {

char a;
int* c;
char b;

};
This is implementation-dependent, but it has to do with alignment. On
some architectures, variables may be required to start at certain
addresses, or the computer may be able to access them much more
efficiently if they start at certain addresses. Therefore, the compiler
is free to add padding to meet these alignment restrictions.

For example, suppose you are on a 32-bit architecture, char is 8 bits,
and int* is 32 bits. Also suppose that the alignment rules for your
system say that int* must start at the beginning of a 32-bit word (i.e.,
a multiple of 4 bytes/octets).

In the first case, suppose char a has a starting address of Start. Then
char b might be placed at (Start + 1). Then, in order to get int* c to
meet the alignment requirement, the compiler will add 2 bytes of padding
between b and c, so that c will start at (Start + 4).

In the second case, char a will be at Start. Then, the compiler will
add 3 bytes of padding so that c starts at (Start + 4). Finally, char b
will be placed at the next available slot, (Start + 8). Then, in order
to account for the situation where e.g. classes need to also start at
the beginning of a word (like when placing them in an array), it may
even add 3 extra padding bytes after b in order to make the entire class
a multiple of 4 bytes.

Some compilers have switches that will let you control whether or not
padding is used. However, as said earlier, this is system dependent.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Feb 21 '07 #3
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 -

Feb 21 '07 #4
On Feb 21, 4:03 pm, "Salman" <salman0...@gma il.comwrote:
I want to know abt the size of the class using sizeof function.
Please note that sizeof is *not* a function, it is a compile time
operator.

Feb 21 '07 #5
On Feb 21, 11:11 pm, "tragomaskhalos " <dave.du.verg.. .@logicacmg.com >
wrote:
On Feb 21, 4:03 pm, "Salman" <salman0...@gma il.comwrote:
I want to know abt the size of the class using sizeof function.

Please note that sizeof is *not* a function, it is a compile time
operator.
Thanks alot all of u for providing me such great answers, also thanks
to tragomaskhalos for correcting me.

Feb 21 '07 #6
In article <11************ *********@m58g2 000cwm.googlegr oups.com>,
sa********@gmai l.com says...
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
That's not at all surprising -- the first item in a struct/class has to
be at the very beginning of the class. The compiler can insert padding
bytes after any member to align a subsequent member to a boundary that
may be necessary for access of that size of item, or perhaps just to
optimize access to that item.

The required and/or desired alignment for an item typically depends on
the item's size. A struct/class will typically have its smallest size
when arrange the members in descending order by size. Of course, the
sizes of some types can vary from one implementation to another, but you
can usually at least come close (e.g. the size-ordering of integer types
is specified in the standard).

--
Later,
Jerry.

The universe is a figment of its own imagination.
Feb 24 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
4514
by: wired | last post by:
Hi, I've just taught myself C++, so I haven't learnt much about style or the like from any single source, and I'm quite styleless as a result. But at the same time, I really want nice code and I go to great lengths to restructure my code just to look concise and make it more manageable. When I say this, I'm also referring to the way I...
4
4419
by: vijay | last post by:
I have a doubt with size of classed with virtual functions I have declared A,A1,A2 ,B , C, D some classes with no varaibles but a vitual function each, The size of A is as expected 4 bytes with one vtbl ptr BUt when I derive the class B from class A (both have 1 virtual function each ) the size remains still as 4 bytes . class A ...
18
2514
by: Tarundeep | last post by:
hi, let us say it is a 32 bit processor then the size of the pointer is 32 bits. now i want to know what would be the size of the class with vtable pointer in it , that is it has few virtual functions. Since the very first location of the object memory points to the vtbale hence that should be 32 bit.
3
1796
by: ThazKool | last post by:
Is there anyway to write a class or struct that has no storage. It only operates on a reference to an already existing type. This is actually an extension to another thread. The thread went a little off of what I was looking for. Hence this new thread. Thanks, ThazKool
6
2292
by: dddddddd2444444 | last post by:
Hi,please help... It works fine when I define a 2-D array like char code. But it won't work when I try to define the array dynamically using a function. It just crashes. Does anyone know why? The compiler i'm using is Dev c++. #include <stdio.h> #include <stdlib.h>
6
4998
by: Laurent | last post by:
Hello, This is probably a dumb question, but I just would like to understand how the C# compiler computes the size of the managed structure or classes. I'm working on this class: public class MyClass {
45
2852
by: charles.lobo | last post by:
Hi, I have recently begun using templates in C++ and have found it to be quite useful. However, hearing stories of code bloat and assorted problems I decided to write a couple of small programs to check. What I expected was that there would be minor code bloat and some speed improvement when using templates. However... I wrote a basic...
18
24942
by: Diogenes | last post by:
Hi All; I, like others, have been frustrated with designing forms that look and flow the same in both IE and Firefox. They simply did not scale the same. I have discovered, to my chagrin, that IE7 does not seem to offer any way to control the font size of a text input element.
11
2626
by: mast2as | last post by:
This question has been posted to this forum before and I read the thread but found that the answers were perhaps imcomplete, so I am trying again. Whenever I am creating objects I would like to keep track of the memory which is used for each object (for stats purpose). They are 2 basic approaches, one is to write a Memory manager type of...
6
2574
by: webinfinite | last post by:
Hi, How to find a STL class size, for example: string. I would like to know what the size of the implementation of this class, I am not interested in the size of its object but the class itself. There are discussion regarding addition of all the data member of the class/ structure to find out its size, but is there a neat way to find out...
0
7700
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7614
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8125
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7974
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3642
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1221
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.