I have a simple Message class and a simple SerialPort Class. I also have a specific message subclass and a specific serial port subclass (CustomMessage & CustomSerialPort):
class Message
{
public:
uint8 getLength() const ( return m_length; }
const uint8* getData() const { return m_contents; }
...
}
class SerialPort
{
public:
bool OpenSerial(int32& errcode);
bool ReadFromSerial(int32& errcode, Message& msg);
bool WriteToSerial(int32& errcode, Message& msg,
uint32* const nBytesWritten);
...
}
Here are the custom classes. Note that I overloaded the WriteToSerial() to take CustomMessage instead of just Message.
class CustomSerialPort : public SerialPort
{
public:
bool WriteToSerial(int32& errcode, CustomMessage& msg,
uint32* const nBytesWritten);
...
}
class CustomMessage : public Message
{
// lots of stuff for messages to specific device
}
Also important, the implementation of CustomSerial::WriteToSerial and CustomMessage::toMessage()
bool CustomSerialPort::WriteToSerial(int32& errcode, CustomMessage& msg,
uint32* const nBytesWritten)
{
SerialPort::WriteToSerial(errcode, msg.toMessage(), nBytesWritten);
}
Message& CustomMessage::toMessage()
{
Message* msg = new Message(m_contents, m_length);
return *msg;
}
You can see that I call the WriteToSerial of the SerialPort class and send it a CustomMessage that has been converted to a Message.
My question is this: where should I delete the message that I created to pass to SerialPort::WriteToSerial?
Or, should I do something more like this:
bool CustomSerialPort::WriteToSerial(int32& errcode, CustomMessage& msg,
uint32* const nBytesWritten)
{
// don't use new
Message m(msg);
SerialPort::WriteToSerial(errcode, m, nBytesWritten);
// deleted when goes out of scope
}
Then, with option 2, if my understanding is correct, I just need to make a Message constructor that takes a parameter of CustomMessage… wait… that seems weird.. taking a child class object parameter in a parent class constructor. Do I need to rethink this?
You don’t need to
new Messageinside toMessage() and you don’t need to delete it.Change
to
When
toMessage()is called in WriteToSerial, it will be bind till WriteToSerial() function finishes.Also you need to add const qualifier to all functions take
Messageas input