Static_cast in C
A cast operator is a unary operator that demands the conversion of one data type into another.
Four casting types are supported by C++:
In this article, we will discuss about the static_cast in depth.
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:
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.
It will give us an error like; error: invalid 'static_cast' from type 'char*' to type 'int*'
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.
Constructor is Called now Conversion Operator is Called Constructor is Called now Conversion Operator is Called Constructor is Called
Let's try to figure out the output from above, line by line:
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.
The above code will compile perfectly.