I have polymorphic classes and I want to convert an object via dynamic_cast<B>(A) although with compiler optimization /GR I receive a message that it may cause undefined behavior. I’m using static_cast instead, but it does no run-time checks and is unsafe for my classes. Also is it valid to return a stack CString object from a class?
CString CKingdomWar::GetTeamName( eUserTeam eTeam )
{
if( eTeam == ELDAR )
return CString( "Eldar" );
else if( eTeam == ELWYN )
return CString( "Elwyn" );
else if( eTeam == NORGNAGON )
return CString( "Norgnagon" );
return CString( " " );
}
As already commented, your CString is returned by value and it’s not a problem.
Regarding the static/dynamic casting, you should show the specific code that gives the warning. You don’t normally get such warnings if you use
dynamic_castcorrectly (that is, to convert pointers or references between compatible types).If
dynamic_cast<B>(A)is to work, then A and B should both be a pointer or reference to an object in the same inheritance tree. For instance, if you had:Then
dynamic_cast<B*>(inst)is okay. Same deal with references. Ifinstis not of type B then the pointer version will return NULL, or the reference version will throw an exception.However, you can’t do this: