Jump to content

static_cast

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Hz.tiang (talk | contribs) at 08:07, 17 January 2016 (Reverted good faith edits by 209.6.207.188 (talk). (TW)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In C++ type conversion, the static_cast operator does an explicit type conversion.[1]

Syntax

static_cast<type> (object);

The type parameter must be a data type for which there is a known method for converting object to, whether this be a builtin or through a casting function. It can be a reference or an enumerator. All types of conversions that are well-defined and allowed by the compiler are done using static_cast.[2]

The static_cast operator can be used for operations such as

  • Converting a pointer of a base class to a pointer of a derived class,
  • Convert numeric data types such as enums to ints or ints to floats.

However, static_cast conversions are not necessarily safe as no run-time type check is done which can cause casting between incompatible data types, for example pointers. However, this is checked at compile time to prevent casting obvious incompatibles. Also, static_cast between pointer of a virtual base to pointer of derived is not allowed, because of the object layout model.

See also

References

  1. ^ Programming: Principles and Practice Using C++. United States of America: Addison-Wesley. 2008. p. 594. ISBN 0321543726.
  2. ^ Thinking in C++. United States of America: Alan Apt. 2000. p. 857. ISBN 0-13-979809-9.