First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast
or return NULL
pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:
DerivedType m_derivedType = m_baseType;
Here there is no casting. You are creating a new object of type DerivedType
and try to initialize it with value of m_baseType variable.
Next line is not much better:
DerivedType m_derivedType = (DerivedType)m_baseType;
Here you are creating a temporary of DerivedType
type initialized with m_baseType
value.
The last line
DerivedType * m_derivedType = (DerivedType*) & m_baseType;
should compile provided that BaseType
is a direct or indirect public base class of DerivedType
. It has two flaws anyway:
static_cast<DerivedType *>(&m_baseType)
BaseType m_baseType;
so any use of m_derivedType
pointer will result in undefined behaviour.