void foo(MyClass* myClass)
{
BaseClass* pBaseClass = dynamic_cast<BaseClass*>(myClass);
delete myClass; // <-------------- Does this affects on pBaseClass ?
}
In general how dynamic_cast
actually works? (does it work like a copy constructor?)
No, that is not safe. dynamic_cast
is just a type conversion - both the original and converted pointer point to the same object.
It is possible the converted pointer will point to a slightly different address (if multiple inheritance is involved), but it's still pointing (in)to the same object - no object copying occurs.
Edit: I mean "not safe" in the sense "after you delete myClass
, pBaseClass
is a dangling pointer." It is still legal code, though. Just quite dangerous.
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With