JiiPee <
n...@notvalid.com> wrote in news:CcC%v.728797$Fy6.4...@fx25.am4:
> On 12/10/2014 01:18, Mr Flibble wrote:
>> On 12/10/2014 00:55, JiiPee wrote:
>>> void f2(B *b) {
>>> B *b1 = nullptr;
>>> if( typeid(*b).name() == typeid(D1).name() )
>>> b1 = new D1(*(reinterpret_cast<D1*>(b1)));
>>> else if( typeid(*b).name() == typeid(D2).name() )
>>> b1 = new D2(*(reinterpret_cast<D2*>(b1)));
>>> }
You can compare directly typeid-s, no need to fetch out the names
(besides, comparing names is not guaranteed to work, they can all be
empty strings legally IIRC).
>>
>> You should use static_cast not reinterpret_cast when casting from base
>> to derived.
>
> why not dynamic_cast? It would check if the conversion is valid, static
> cast does not.
Dynamic_cast is performed at runtime and can be quite slow. It would be
silly to use dynamic_cast if you have just found out by comparing typeids
that the conversion would be valid (maybe only in debug-build asserts, to
verify you have not made a mistake in the code).
A virtual clone function is still the best solution for the cloning
problem: probably faster than the repeated if-else typeid check and also
more scalable and maintainable.
Cheers
Paavo