in my program I have 2 headers (IP and MAC headers) that are 'sons' of GeneralHeader. All General, IP and MAC headers classes have PrintMe() function. In addition, I have a Packet class that holds list of GeneralHeaders (the list actually may have IP or MAC headers: (without IP defenition, to shorten):
//Packet.h
class GeneralHeader {
public:
bool Valid;
HeaderType_t HeaderType; // MAC or IP
virtual void PrintMe();
};
class HW_MACHeader: public GeneralHeader {
public:
long unsigned DestAddr:48;
long unsigned SourceAddr:48;
virtual void PrintMe();
};
struct NetworkPacket_t {
NetworkPacket_t();
list<GeneralHeader> Headers;//TODO GeneralHeader
void PrintMe();
};
I have dificulty to implement the PrintMe() method that will print the list of GeneralHeaders using the appropriate for MAC or IP PrintMe() method (not the base PrintMe() of GeneralHeader):
//Packet.cpp
//This implementation prints GeneralHeaders :(
//(although MAC headers were added to the Headers list)
void NetworkPacket_t::PrintMe() {
list<GeneralHeader>::iterator it_H;
for (it_H = Headers.begin(); it_H != Headers.end(); ++it_H) {
it_H->PrintMe();
};
};
Another try was to cast the iterator it_H to appropriate MAC or IP header (according to HeaderType), but whichever way i tried to cast it, it did not work, e.g.:
//Packet.cpp
//Casting implementation
//Here I get run error:
//terminate called after throwing an instance of 'std::bad_cast'
void NetworkPacket_t::PrintMe() {
list<GeneralHeader>::iterator it_H;
for (it_H = Headers.begin(); it_H != Headers.end(); ++it_H) {
switch (it_H->HeaderType) {
case General_Header_type:
std::cout << " General Header " << endl;
it_H->PrintMe();
break;
case MAC_Header_type:
dynamic_cast<HW_MACHeader&>(*it_H).PrintMe();
break;
default:
std::cout << " default" << endl;
};
};
};
I really appreciate any help you can prvide