Among static_cast, dynamic_cast, reinterpret_cast and const_cast, only static_cast is able to return an object of desirable type, whereas the other type can return only pointer or reference to representation. Why is it so?
Examples:
int y = 3;
double z = reinterpret_cast<double> (y);//error
double z = reinterpret_cast<double&> (y);//ok
double z = static_cast<double> (y);//but this is ok!!!
const int y = 3;
int z = const_cast<int> (y);//error
int z = const_cast<int&> (y);//ok
and for dynamic_cast:
using namespace std;
class Gun
{
public:
virtual void shoot(){
cout << "BANG!\n";
}
};
class MachineGun : public Gun{
public:
void shoot() override{
cout <<"3X-BANG\n";
}
};
int main()
{
Gun gun;
MachineGun tt;
Gun* gunp = &gun;
Gun* gunp1 = &tt;
Gun* newGun = dynamic_cast<Gun*>(gunp1);//ok
Gun newGun1 = dynamic_cast<Gun>(tt);//error
}
I'm making attempt to explain based on example, as addition to other answer that did explain nature of casts.
This is not one of 11 allowed casts with
reinterpret_cast. Alsostd::bit_castcan't cast it on most platforms as theinttypically does not have enough bits fordouble. So it is unsure what you wanted to achieve.This is present in list of valid
reinterpret_castbut likely causes undefined behaviour for same reason whystd::bit_castrefuses. In typical implementation yourzis bigger thanyand so takes bits beyond memory location ofy. In such places preferstd::bit_castthat does not compile to undefined behaviour but refuses to compile.But that is fully valid. It is effectively same as
Compilers do not even warn about the latter. However when the value range of
ydoes not fully fit tozthen it is not clear if it was intentional. On such cases it is better to use former to indicate intent.That is good. Absurd
const_castdoes not compile! Or how does the effect that you tried to achieve differ from lot more readableI would write that. Please describe the situation where you would write former.
Works, but is similarly unneeded and confusing like previous. I would only use
const_castfor situations like that:Here I know that thing referred by reference to const
yis really not const originally and so it is not undefined behaviour to modify it to42.About
dynamic_castyour example does not make sense at all what it wants to do:It could be perhaps trying to do something like that:
That compiles. However that results with
newGun1initialised with sliced outGunbase sub-object ofMachineGun ttand that is often programming error. What you tried to achieve with cast remains totally dark however.