Construct an object from a "dumb" base class

I have created a "smart version" of the standard structure - there struct canmsg

, provided by the system, data of this type is read from the can device, and I often process such frames.

Now, to simplify the processing of I created child class: class TCanFrame : public canmsg

. It doesn't have any additional properties, but it does have many methods - a friendly constructor for creating frames from scratch, commands and data, getters and setters that read and set various abstraction layer above properties (for example, channel-encoded subaddresses in data ).

What is the best way to construct an object of type TCanFrame from an instance struct canmsg_t

? Can I just do memcpy from &source

to this

? Or will I need to copy it across the field? Or some other trick to have a neat TCanFrame instantiated from "dumb" canmsg

Or maybe I can get the copy constructor to accept the parent class?

+3


source to share


2 answers


You can use the default copy constructor provided by the compiler:



TCanFrame(const canmsg& msg) : canmsg(msg) {}

      

+4




If you are not adding any data items and do not need access to protected members canmsg

, then I think you should not create a derived class. Instead, you can add free functions to perform additional functions in the namespace where it is canmsg

defined, and then use them with regular objects canmsg

. You can read more about the "non-member interface" of a class and why it's good. these articles by Scott Myers and Herb Sutter .



Also note that if you are creating a derived class and canmsg

does not have a virtual destructor, you can easily run into undefined behavior by calling delete

on canmsg*

, which actually points to TCanFrame

.

+6


source







All Articles