Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a POD is wrapped inside a class, does it give the same effect?

Tags:

c++

class

wrapper

Following are 2 different interpretations:

char c;  // 1
struct MyChar { char c; };  // 2

If I do new MyChar[100], will it allocate 100 bytes in all platform ? Adding non-virtual constructor/destructor and/or operators will make any effect on the size of MyChar ?

like image 552
iammilind Avatar asked Nov 29 '25 23:11

iammilind


2 Answers

MyChar may have unnamed padding bytes after c, so no, it isn't guaranteed that sizeof(MyChar) is 1.

like image 81
James McNellis Avatar answered Dec 02 '25 13:12

James McNellis


On MSVC, you can use:

#pragma pack(1)
struct MyChar 
{ 
    char c; 
}; 

// Restore
#pragma pack()
like image 38
Ajay Avatar answered Dec 02 '25 14:12

Ajay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!