Static Cast In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Static Cast In C++

Static Cast In C++

BLUF: Mastering Static Cast In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Static Cast In C++

C++ is renowned for its efficiency. Learn how Static Cast In C++ enables low-level control and high-performance computing in the tutorial below.

C++ programming stands out as a robust and versatile language that provides several typecasting possibilities. One of these strategies is the static cast, a method that allows developers to convert one type to another in a clear and direct manner. In this post, we will explore the format, uses, and benefits of the static cast feature in C++. Additionally, we will present examples of code snippets along with the outcomes they produce to assist you in comprehending this concept. By the end, you will possess a solid understanding of static casting and will be ready to apply it with assurance in your C++ projects.

Type casting in C++ involves converting one data type to another. By employing the static cast operator, you can perform explicit type conversions in a straightforward and secure manner. This approach handles type conversions during compilation instead of execution, resulting in improved speed and reduced error risks, hence the term "static".

The syntax for a static cast is as follows:

staticcast<newtype>(expression);

In this scenario, the expression represents the specific value or variable requiring casting, with new_type indicating the intended type. When the conversion is a valid and explicitly defined action, the static cast operator endeavors to execute it.

Basic Static Cast

Let's begin with a simple illustration to demonstrate the functionality of static cast operations. Consider a scenario where there is a necessity to convert an integer into a floating-point value. Here is the solution:

Example

#include <iostream>

int main() {
    int num = 42;
    float result = static_cast<float>(num);

std::cout<< "Result: " << result <<std::endl;

    return 0;
}

Output:

Output

Result: 42.0

Explanation:

In this example, we clearly convert the integer num to a floating-point value by employing a static cast. The transformation is executed through the static cast operator (float), and the result is stored in the result variable. The fact that 42 is displayed as 42.0 in the output confirms the success of the conversion.

Class Conversion with Static Cast

If a valid association exists between the classes, like inheritance or explicit conversion operators, static cast can be employed to convert pointers or references between classes. Let's illustrate this with the following scenario:

Example

#include <iostream>

class Base {
public:
    virtual void display() const {
std::cout<< "Base class" <<std::endl;
    }
};

class Derived : public Base {
public:
    void display() const override {
std::cout<< "Derived class" <<std::endl;
    }
};

int main() {
    Base* basePtr = new Derived;
basePtr->display();

    Derived* derivedPtr = static_cast<Derived*>(basePtr);
derivedPtr->display();

    delete basePtr;

    return 0;
}

Output:

Output

Derived class
Derived class

Explanation:

In this example, there is a fundamental class named Base and a subclass named Derived that inherits from Base. We create a basePtr pointer of Base type and point it to the address of a dynamically allocated Derived object. By employing a static cast, we convert basePtr into a pointer of type Derived and assign it to derivedPtr. The result illustrates the effective invocation of the overridden method in the subclass when utilizing both pointers to invoke the display function.

Conclusion:

Finally, static casting plays a vital role in C++ by allowing developers to perform explicit type conversions. It offers a reliable and efficient way to switch between different types, be it classes with inheritance connections or basic data types. Mastering the syntax and usage of static cast empowers programmers to manage type conversions effectively, ensuring both safety and efficiency in their code.

In the previous article, we explored the syntax of static casting and provided detailed code samples along with corresponding outcomes. We demonstrated the versatility of static casting in different scenarios, ranging from simple conversions among basic data types to intricate conversions involving class inheritance structures.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience