We've been doing this for 50 years, you don't need a class hierarchy for your event struct.
enum EventType {
EVENT_NONE,
EVENT_TEMPERATURE_READING,
EVENT_SMOKE_DETECTED,
EVENT_CARBON_MONOXIDE_DETECTED,
};
struct Event {
EventType type;
union {
TemperatureDeadingData temperature_reading;
SmokeDetectedData smoke_detected;
CarbonMonoxideDetected carbon_monoxide_detected
} data;
};
std::vector<Event> events;loading story #50178193
loading story #50177885
loading story #50177433
Yes, though in modern C++, don't do this, use std::variant instead. It has better type-safety (nothing stops you from writing to one member of the union but reading from another, causing UB) and handles lifetimes much better. Your version leaks, because struct Event wont destruct any of the nested types inside the union, and in the example, they have heap-allocated data (std::strings and the like). In order to that properly with a tagged union, you need to define the destructor of Event yourself (which is not done in your example) and call the correct destructor manually of the active union member.
Tagged unions (especially with resource-managing types) is hard to implement correctly in C++ (and not trivial in C either). Don't do it, use std::variant.
loading story #50177352
loading story #50188989
loading story #50177480
loading story #50177405