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.