I created a "smart variant" of a standard structure - there's the struct canmsg provided by the system, data of that type is read from a can device, and I frequently handle such frames.
Now, for easier handling them I created a child class: class TCanFrame : public canmsg. It doesn't have any extra properties, but it has a bunch of methods - a friendly constructor for creating the frames from scratch, commands and data, getters and setters that read and set different properties "abstraction layer above" (e.g. channel subaddresses encoded in data).
What is the best method of constructing an object of the type TCanFrame from an instance of struct canmsg_t? Can I just do a memcpy from &source to this? Or would I need to copy it field-by-field? Or some other trick to have a neat TCanFrame instance created out of "dumb" canmsg Or maybe can I make the copy constructor to accept the parent class?
If you don't add any data members, and don't need to access any protected members of canmsg, I think you shouldn't create a derived class. Instead, you can add free functions to do the extra functionality into the namespace where canmsg is defined, and then use them with normal canmsg objects. You can read more about a class's "non-member interface" and why it's a good thing in e.g. these articles by Scott Meyers and Herb Sutter.
Also note that if you do create a derived class and canmsg doesn't have a virtual destructor, you can easily run into undefined behaviour by calling delete on a canmsg* which actually points to a TCanFrame object.
You can use default copy constructor provided by the compiler:
TCanFrame(const canmsg& msg) : canmsg(msg) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With