+ 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?
8 Respostas
+ 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.
+ 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
+ 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 :)
+ 3
sorry asking too much... 😅
+ 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.
+ 3
KrOW and Schindlabua
Thanks for your help..
+ 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?
+ 2
Schindlabua, Can i ask when or which situations that can cause padding when declare some class?