Tuesday, August 13, 2013

four type of cast

four type of cast
syntax:
reinterpret_cast <new_type> (expression)
dynamic_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)


1.reinterpret_cast
to interpret a value as a different type.
  • pointer->intergers
  • intergers-> pointer
  • pointers from one type to another type


2.dynamic_cast
used with pointers and references to objects
we can not cast a base class to derived class

CBase b;
CBase* pb;
CDerived d;
CDeried* pd;

pb = dynamic_cast<CBase*>(&d);
pd = dynamic-cast<CDerived>(&b);  //wrong: b is base class and it does not have the derived class parts

--------------------------------------------------------------------------------------------------------------

CBase* pba = new CDerived;
CBase* pbb = new CBase;

CDerived* pd;
pd = dynamic_cast<CDerived*>(pba);

pd = dynamic_casr<CDerived*>(pbb);  //wrong; pbb is base class and can not cast to a derived class


3.static_cast

perform automatically and can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to it derived.

it will have some run-time errors;


4.const_cast
这种类型转换对常量const 进行设置或取消操作:
this type of casting manipulates the constness of an objects,either to be set or to be removed.
for example, in order to pass a const argument to a function that expects a non_constant parameter:

const char* c ="sample text"; // const
print(const_cast<char*> (c));  cast the const char* to a char*

No comments:

Post a Comment