e1->getMessage()
returns an object of type Message, not a pointer. So your data will be sliced. Additionally you cast a pointer to a temporary here:
Message2 *m2 = static_cast<Message2*>(&e1->getMessage());
You can do this if you return a pointer.
Message * getMessage() { return &theMessage; }
static_cast
is the correct way of casting base pointers to derived pointers without any runtime checks. The "safer" way of doing this is to use dynamic_cast operator of course, since it will perform a runtime-check upon casting a derived to a base pointer or reference. (I guess I'm going to be stoned to death here if I tell you to stick to static_cast
to avoid those checks if you got your own that is fail-proof. ;))
The best way (in my opinion) would be a proper virtual interface design in the base classes. You could avoid casting from base to derived this way.
Additionally you slice all your Event
s if you use a vector<Event>
. You can only use vector<Event*>
to have your collection of derived objects since a Base pointer may point to derived objects but Base objects cannot hold Derived Data. (All derived Event
s in your vector will miss theMessage
and only have the data contained in Event
.)