(Note that class
isn't a valid variable name, since it's a keyword. I'll call it c
instead).
Is it safe to delete the pointer after dynamic_casting?
Yes; but beware that both pointers are invalid after deleting the object that they point to. You can't use either pointer value afterwards.
In general how dynamic_cast actually works?
It converts a pointer or reference to a class type into a pointer or reference to a different class type, with a run-time check that the conversion is valid. In this case, the cast will succeed (giving a valid pointer) if BaseClass
is the same as, or a base class of, the dynamic type of the object. It will fail (giving a null pointer) otherwise.
If you were casting *c
to a reference type, then failure would cause an exception (std::bad_cast
), since there is no such thing as a null reference.
does it work like a copy constructor?
No. Copy constructors are for copying the object. This isn't copying it, just changing the type of a pointer that points to it. A copy would look like
BaseClass bc = *c;
Note that the type of bc
is BaseClass
, not the type of c
(which is presumable a class derived from BaseClass
); this is known as "slicing", since the derived part of the object is "sliced off" and not copied.