First of all, your class hierarchy looks suspicious. From what you showed, there is no connection between B and C , except for the existence of a third type, A , which contains the object B and the pointer C Still, the type of the variable inside B must depend on which subclass of C this pointer points to inside the object A ?
This seems like an unnecessary connection. Why not just include this field B in the corresponding subclasses of C ?
Assuming that you have corrected your class hierarchy, you still have a relatively straightforward problem with the need to send one of two different types of messages (different sizes) through the socket. Here is one solution:
enum message_type {type1, type2}; class message_type1 { ... }; class message_type2 { ... }; // when sending message (pseudocode) write message_type variable write message_type1 object OR message_type2 object // when reading message (pseudocode) read message_type variable if type1 read message_type1 object else read message_type2 object
Of course, message_type1 and message_type2 can be related, being subclasses of the same base class or instances of the same template, etc., to avoid repetition if the two types of messages have some common features.
EDIT . You mentioned in comments on other answers that you cannot split your message into different packages. Can you explain what this means? A “packet” is not an exact term: TCP has segments, UDP and IP have datagrams, and Ethernet has frames. None of them has any relation to how many times you call send() on a socket (i.e., two calls to send() ) do not necessarily mean that two TCP segments are sent, and vice versa, before send() does not guarantee that your data will be transferred in one segment).
source share