Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ call different class constructors, avoid switch

I'm capturing a network packet in my program as a char* array. The first byte of the array represents the type of packet I received and for each type I want to have a separate child class of my generic Packet base class to which I pass the byte array and where it will be interpreted.

I would like to avoid using a switch statement where the packet's first byte would be evaluated and the according constructor called. Firstly because in OOP you should avoid switch clauses and secondly because I don't want to add a separate case to the switch statement every time I add a packet class.

I looked into the Factory Method pattern, but I'm not sure how that would help me in this situation or if it would solve my problem at all.

Basically what I want to avoid is editing my code at 10 different places just to add a single packet class.

like image 767
MikeTysson Avatar asked Feb 10 '26 22:02

MikeTysson


1 Answers

"I would like to avoid using a switch statement ..."

At some point you'll need to discriminate upon this byte, no matter if you're doing so in a factory or elsewhere.

A way to avoid switch, is to create a map of create_class functions, and find and call these according the map key (the discriminating byte value).

This solution will have the advantage, that you can easily add further keys and create_class functions, without changing the basic factory code.

like image 69
πάντα ῥεῖ Avatar answered Feb 16 '26 17:02

πάντα ῥεῖ