Javatpoint Logo
Javatpoint Logo

Static_cast in C

Introduction:

A cast operator is a unary operator that demands the conversion of one data type into another.

Four casting types are supported by C++:

  • Static Cast
  • Dynamic Cast
  • Const Cast
  • Reinterpret Cast

In this article, we will discuss about the static_cast in depth.

Static Cast:

The simplest cast that can be used is the static cast. It is a cast done at compile time. It can call explicit conversion functions as well as perform implicit type conversions (such as converting an int to a float or a pointer to a void*).

Syntax of static_cast

The syntax of static_cast are as follows:

Dest_type will be the return value of static_cast.

A static_cast example

The C++ program to implement static_cast is shown below:

Output:

The Value of a: 5
The Value of b: 5

Different Scenarios and the Behaviour of static_cast:

1. Static_cast for references to primitive data types:

Let's now modify the code mentioned above a bit.

Output:

It will give us an error like;
error: invalid 'static_cast' from type 'char*' to type 'int*'

Explanation:

It means that the static_cast will prevent you from typecasting an object pointer into another even when doing so is against the law.

2. Using a User-Defined Conversion Operator to Convert an Object

If a class's conversion operator is defined, static_cast can invoke it. Take yet another instance of an object being converted to and from a class.

Output:

Constructor is Called
now Conversion Operator is Called
Constructor is Called
now Conversion Operator is Called
Constructor is Called

Explanation:

Let's try to figure out the output from above, line by line:

  1. The constructor, which in this case is actually a conversion constructor (C++14 regulations have changed slightly), is called when the object (obj) is created.
  2. Since we defined the Conversion operator, the compiler won't throw an error when you generate str from obj.
  3. You are actually invoking the conversion constructor when you make obj = 20.
  4. Making str2 from static_cast is very similar to making string str = obj; with strict type checking.
  5. Static_cast is used to change 30 into an integer when you write obj = static_cast Int> (30).

3. C++'s static_cast for inheritance

In the case of inheritance, static_cast can offer both upcasting and downcasting. The use of static_cast in the context of upcasting is seen in the following example.

Explanation:

The above code will compile perfectly.

  1. We explicitly cast the address of d1 into Base and saved it in b1.
  2. We got the address from d1, converted it to Base using static_cast, and then put it in b2.
  3. In the above example, the base class was inherited as public.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA