Jump to content

static_cast

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by DannyS712 bot (talk | contribs) at 18:35, 11 May 2020 (Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags). 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 performs an explicit type conversion.[1]

Syntax

static_cast<type> (object);

The type parameter must be a data type to which object can be converted via a known method, whether it be a builtin or a cast. The type can be a reference or an enumerator. All types of conversions that are well-defined and allowed by the compiler are performed 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 non-virtual derived class;
  • converting numeric data types such as enums to ints or ints to floats.

Although static_cast conversions are checked at compile time to prevent obvious incompatibilities, no run-time type check is performed that would prevent a cast between incompatible data types, such as pointers. Also, the result of a static_cast from a pointer of a virtual base class to a pointer of a derived class is undefined.

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. pp. 857. ISBN 0-13-979809-9.