0

Consider the following code:

#include <iostream>
#include <conio.h>> 
using namespace std;

class book 
{ 
    char Title;
    int no_of_pages; 
public: 
    void read(); 
    void show(); 
}; 

int main()
{
    book ob;
    char Title;
    cout << sizeof(book) << " " << sizeof(Title) << endl;

    getch();
    return 0;
}

The output of the code is

8 1

If I change the definition of 'Title' in the class to following:

char Title[5];

and the main() 'Title' to

char Title[5];

the output changes to:

12 5

To see if this is something which is done to all string variables in the program, I used the 'Title' in main(). But, the pattern is apparent for a string declared in a class.

For the sake of completion, the pattern is :

Size of character array is taken to be the least multiple of 4 greater than the actual size of array

Question: Although I understand it is implementation dependent, does anyone know or can suggest a reason for this behaviour of C++ 11?

My compiler is VS 2012, for 64-bit Windows.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
Cheeku
  • 833
  • 1
  • 8
  • 22

2 Answers2

1

An int has typically a size of four bytes, and typically the compiler tries to store it in memory with four byte alignment.

In your class named "book", the "Title" char is stored at offset 0 with size 1 (char has always size 1 by definition). So where do you think should no_of_pages be stored? At offset 1, 2 or 3, it wouldn't be stored with four byte alignment. So it is stored at offset 4, occupying four bytes, which makes the total size of "book" four bytes. At the cost of wasting three bytes, every access to no_of_pages is faster.

Actually, if you look at this code:

book book1 = ...; 
book book2 = book1;

The second assignment needs to copy eight bytes. On a typical 64 bit computer, this is done by loading 64 bit from book1 into a register, then storing that register to book2. Two instructions. Copying five bytes would be much more complicated.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
0

It's padding. The character array is 5 bytes long, so if no_of_pages would be stored directly after the array, it would be stored at bytes 6 through 9 (relative to the beginning of the object). However reading values from memory is more efficient if they're properly aligned, so it would be better if it was stored in the bytes 8 through 11. Therefore 3 bytes of padding are added between the end of the array and the beginning of no_of_pages. These 3 bytes are not part of the size of the array (that is the array is still 5 bytes), but they are part of the size of the object because they're inside the object.

sepp2k
  • 363,768
  • 54
  • 674
  • 675