Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of #pragma pack on a class

Tags:

c++

class

pragma

Can we use #pragma pack() before a class?

What is the significance of pragma here? I know it is used for giving information to compiler regarding implementation, but what if we use it with a class?

like image 525
Satya Kumar Avatar asked Dec 05 '25 17:12

Satya Kumar


1 Answers

It has the exact same effect on a class as it does on a struct, affecting the alignment of data members.

Actually using it on a class is very unusual and almost always a mistake. The layout of a C++ class object is heavily implementation defined. A C++ compiler usually makes an effort to optimize that layout, dropping the v-table pointer when it can. And potentially adding one when the class uses multiple inheritance. So a minor change to the class declaration, like making a method virtual or adding a base class can significantly alter the object layout. This will then of course break the code that depends on that pragma. Like an object serialized to a binary file won't deserialize properly anymore. In general a bad practice too but happens all the time anyway. Don't use it.

like image 184
Hans Passant Avatar answered Dec 08 '25 10:12

Hans Passant



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!