You are here:

C++/sizeof() operator


QUESTION: Following is my code:
using namespace std;
class A
char b;
int a;
static int c;
int main()
A ob;

Here its outputting 8
According to me int takes 4,char takes 1 and static will aslo take 4. so it shoulb be 9. But its taking 4 for int, 4 for char and 0 for static. Please explain how this sizeof() operator works in classes

ANSWER: You are correct, the sizeof char is 1, and sizeof int is 4 (on *this* compiler - it doesn't have to be 4).  However, a compiler can (and often does) align the members to best use the processor.  A 32-bit processor can access memory on 4-byte boundaries more efficiently than unaligned members.

In this case, int a was aligned (making the char take 4 bytes) and the int is 4 bytes.  So the sizeof is 8.  What about the static int?  Static members in classes do not add to the size of the class.  They are allocated outside of the class since there is only one copy of a static.

Most compilers have a #pragma to change padding of structures and classes.  #pragma pack is used by many.  Generally, you should pack only if the class is being transmitted or stored into a file.


---------- FOLLOW-UP ----------

QUESTION: Thanks for the information Bill.. But i have one more doubt. This allignment i Did not understand.. Is it like the variable maximum in size will allign the others? Suppose if i have float variable in the above class then the total size will be 8+8+8=24 as size of float is 8 bits?

The alignment is done to a 4 by boundary by default on a 32 bit processor:

struct {
 int a;    // at 0
 char b;   // at 4
 char c[2];// at 8
 int d;    // at 12
 double e; // at 16 (if it's 8 bytes)
 char f;   // at 24
 short g;  // at 28

Every member of the struct will be on a 4-byte boundary.

I hope this clears it up for you.



All Answers

Answers by Expert:

Ask Experts


Bill A


I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.


I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

BS Computer Engineering

©2016 All rights reserved.