How the code actually work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

How the code actually work?

#include <iostream> class Base { int a; char b; }; int main() { std::cout << sizeof(Base); } Why this code give an output 8?

8th Nov 2018, 5:15 AM
オレンジ
オレンジ - avatar
8 Answers
+ 11
structs are padded, that means if the compiler feels that it's necessary it will add some space in between fields. In your case there will be an extra 3 bytes of padding after the char. This is done to align fields with 32-bit (or 64-bit) boundaries fir faster memory access. Almost all compilers give you a way to disable padding ("pack" the structure) but it's nonstandard and different for each one.
8th Nov 2018, 6:30 AM
Schindlabua
Schindlabua - avatar
+ 5
Read here https://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/amp/ futhermore you have to know that virtual methods/hierarchy add "something" at your objects https://code.sololearn.com/c3qPjk7s3rvi/?ref=app
8th Nov 2018, 7:01 AM
KrOW
KrOW - avatar
+ 3
It all depends on your compiler and computer architecture, but usually an int is 4 bytes and a double are 8, so there will probably no padding. Since both are a multiple of 4! (And a char is 1 byte which will be padded to 4) But I just want to stress that you can't ever rely on how much padding there is or isnt :)
8th Nov 2018, 6:44 AM
Schindlabua
Schindlabua - avatar
+ 3
sorry asking too much... 😅
8th Nov 2018, 7:00 AM
オレンジ
オレンジ - avatar
+ 3
No Problem :D Just round the size of each member to a multiple of 4, that's a good rule of thumb. So a char has 3 bytes of padding because sizeof(char) == 1. You need an additional 3 to get to 4.
8th Nov 2018, 7:04 AM
Schindlabua
Schindlabua - avatar
+ 3
KrOW and Schindlabua Thanks for your help..
8th Nov 2018, 9:16 AM
オレンジ
オレンジ - avatar
+ 2
Schindlabua thanks for answering. Anyway you mean when i declare some class like have two variable (int a and double b) it will give 3 extra bytes?
8th Nov 2018, 6:37 AM
オレンジ
オレンジ - avatar
+ 2
Schindlabua, Can i ask when or which situations that can cause padding when declare some class?
8th Nov 2018, 6:53 AM
オレンジ
オレンジ - avatar