Sunday, November 29, 2009

Static Cast

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

ensures that at least the classes are compatible if the proper object is converted

no safety check is performed during runtime to check the overhead of the type-safety checks of dynamic_cast is avoided.
"class CBase {};
class CDerived: public CBase {};
CBase * a = new CBase;
CDerived * b = static_cast(a);
This would be valid, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.

static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types:
"double d=3.14159265;
int i = static_cast(d); "

Any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.

No comments:

Post a Comment