Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct object from "dumb" base class

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?

like image 427
SF. Avatar asked Jun 12 '26 06:06

SF.


2 Answers

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.

like image 178
Angew is no longer proud of SO Avatar answered Jun 14 '26 20:06

Angew is no longer proud of SO


You can use default copy constructor provided by the compiler:

TCanFrame(const canmsg& msg) : canmsg(msg) {}
like image 43
Anton Savin Avatar answered Jun 14 '26 20:06

Anton Savin



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!