Search code examples
c++inheritanceparentradixvirtual-functions

C++ inheritance calling functions from child on a variable of the parent class


In C++ I have a base class Packet and then a lot of children APIPacket, DataIOPacket etc. Now I want to store an incoming packet and since I don't know the type I store this in a variable:

Packet packet;
packet = DataIOPacket();

But now DataIOPacket has a function getAnalogData(); I can't do:

packet.getAnalogData();

Since packet doesn't have this function. In java I think this is possible since the actual type of the object stored in packet is not lost (is this correct?). But in C++ my DataIOPacket is narrowed into a Packed and loses it's functions that haven't been declared in Packet.

You could make a virtual function in Packet for every function in every child. But for me this would mean a lot of functions in Packet which in most cases should not be called. It has no use calling getAnalogData() on an APIPacket.

How is this problem solved? I can't find the answer but I feel a lot of people must encounter it.

You could do something with typecasting back to DataIOPacket and APIPacket but this doesn't really seem a clean solution either.

Are there maybe libraries that solve my problem?

Rgds,

Roel


Solution

  • This is possible in java and in c++ too. you need to do a dynamic_cast to check for the type.

     Packet* packet;
    packet = new DataIOPacket();
    
          DataIOPacket dio* = dynamic_cast<DataIOPacket*>(packet); 
                if (dio != 0)
                {
                 dio->DoSomeChildMethodStuff();
                }