Class Inheritance and Class Inheritance in C ++

I just discovered from this Q / A that structures are inherited in C ++, but is this good practice or is it preferable to use classes? In what cases is preferable and in what cases not?

I never need it, but now I have a bunch of different types of messages, but the same longitude. I got them in binary format in a char array, and I just copied them with memcpy to the structure to fill in its fields (I don't know if it is possible to do this with std :: copy).

I think it would be great to inherit every structure from a basic structure with common headers, so I searched for this. So, the second question: if I do this using classes, is it possible to make memcpy (or std: copy) from the buffer to the class?

+4
source share
2 answers

If you can use bitwise copying or not, this has nothing to do with the struct or class tag and depends only on whether the struct or class is_trivially_copiable . Are they defined in the standard (9/6 [class]), and basically it comes down to the fact that you don't need to declare any other special member methods than the constructors.

The bitwise copy is then permitted by the standard of 3.9 / 2 [basic.types]

For any object (except a subobject of the base class) of a trivially copied type T , regardless of whether the object has a valid value of type T , the basic bytes (1.7) that make up the object can be copied to a char or unsigned char array. If the contents of a char or unsigned char array are copied back to the object, the object subsequently retains its original value. [Example:

 #define N sizeof(T) char buf[N]; T obj; // obj initialized to its original value std::memcpy(buf, &obj, N); // between these two calls to std::memcpy, // `obj` might be modified std::memcpy(&obj, buf, N); // at this point, each subobject of `obj` // of scalar type holds its original value 

-end example]

Note: a bitwise copy of the fill bytes will result in reports in Valgrind.

Using std::copy with the same effect:

 char const* b = reinterpret_cast<char const*>(&obj); std::copy(b, b + N, buf); 
+5
source

The only difference between struct and class is the default access modifier for its members. In struct it public and in class it private (until specified otherwise). In addition, struct and class identical in C ++. Structures are sometimes preferred for PDO (Plain Data Objects) over reading classes, but this is valid until the coding agreement.

+1
source

Source: https://habr.com/ru/post/1441468/


All Articles