Reputation: 160
I know that you can effectively perform the following code to convert a struct into a byte array,
struct Dummy
{
int a;
int b;
};
Dummy data;
char* buffer = reinterpret_cast<char*>(&data);
Then we can access each of the 8 bytes, one by one, using the char array pointer.
My question is can you do the same with a class in a similar manner?
class Dummy
{
private:
int a;
int b;
};
Dummy data;
char* buffer = reinterpret_cast<char*>(&data);
Upvotes: 0
Views: 869
Reputation: 50046
The only difference between class and struct is the default access modifier which for struct
is public
and for class
is private
. In c++ standard you can actually read about classes while in examples you have structs: https://eel.is/c++draft/class.prop
Technically your code is correct, for example it does not cause undefined behaviour. Strict aliasing rules are not violated - you can use char
type to access stored value of your object:
http://www.eel.is/c++draft/expr.prop#basic.lval-11.3
The question is what you want to do with this pointer? For example, if you want to implement serialization then you need to make sure your class is_trivially_copyable
:
https://en.cppreference.com/w/cpp/types/is_trivially_copyable
Objects of trivially-copyable types that are not potentially-overlapping subobjects are the only C++ objects that may be safely copied with std::memcpy or serialized to/from binary files with std::ofstream::write()/std::ifstream::read().
Your class passes this test:
static_assert(std::is_trivially_copyable<Dummy>::value, "Cannot be copied with memcpy");
You need to also be aware of the various problems such object access can cause: alignments, field padding, packing etc. Under visual studio I used to use #pragma pack(1) to make sure all the fields in the class are byte packed. But this removes many optimizations and should not be used unless there is no other solution.
Upvotes: 1