Hi, i am writing a client for some protocol which has several messages defined. Ive been passing these messages around in a list of type <Message*>, whilst each individual message is derived from Message, let me give a quick example of this, with a message called GRMFYI
Code:
int main (int argc, char** argv)
{
DatReader* dat = NULL;
GameState* gs = NULL;
uint8_t* inpacket;
int packet_size = loadpacket (&inpacket);
uint8_t* tmp = new uint8_t[packet_size];
memcpy (tmp, inpacket, packet_size);
NetworkMessage* inmsg = new NetworkMessage (packet_size, tmp);
inmsg->setPos (4);
Message* m = new GRMFYI (inmsg, gs, dat);
delete m;
delete inpacket;
delete inmsg;
return 0;
}
this is stripped down to absolute basics, but basically when i run valgrind GRMFYI wont be freed, i assume because Message and GRMFYI are different. I can only guess that the wrong deconstructor is being called, as frees are done based on structures in memory (i think). If instead of
Code:
Message* m = new GRMFYI (inmsg, gs, dat);
i use
Code:
GRMFYI* m = new GRMFYI (inmsg, gs, dat);
valgrind gives me a happy pat on the back. My question is is there a way to delete a derived class if you only have a pointer to the base class and are unaware of how the class was derived.
The two obvious solutions are to have an virtual killme () function which does delete this or to add a deleteMessage function to the message factory (i already have one producing the derived classes).
Thankyou