in C ++ my DataIOPacket tapers to Packet and loses functions that were not declared in Packet
This happens because you assign an object of type DataIOPacket object of type Packet , which leads to the fact that this object is sliced ββ(see What is cropping of objects? ).
What you are really looking for is a way that you could find out at runtime whether the object you are working with was created as an instance of a DataIOPacket . In other words, you are looking for Runtime Type Identification (RTTI) .
To avoid slicing, you need to have a link or pointer to an object. The type of this object will be identified at runtime:
Packet* packet; packet = new DataIOPacket();
now Packet is a pointer to an object of type DataIOPacket (runtime), but the pointer type is Packet* (compilation time). To call a method specific to the DataIOPacket class for this object, the compiler needs to know that this pointer points to an object of the type that this method provides. The correct way to reset a pointer to a polymorphic type is to use dynamic_cast , which returns NULL if this object cannot be passed to this type:
Packet* packet; packet = new DataIOPacket(); DataIOPacket* dataIOPacket = dynamic_cast<DataIOPacket*>(packet); if (dataIOPacket) dataIOPacket->getAnalogData();
Please note that this is also possible for objects with automatic storage duration:
DataIOPacket packet; Packet* pPacket = &packet; DataIOPacket* dataIOPacket = dynamic_cast<DataIOPacket*>(pPacket); if (dataIOPacket) dataIOPacket->getAnalogData();
In this case, the Packet type is the decisive factor that decides whether dynamic_cast succeed or not. The object must be created as an instance of DataIOPacket to call the getAnalogData method on it.
source share