static_cast का उपयोग सामान्य/साधारण प्रकार के रूपांतरण के लिए किया जाता है। यह निहित प्रकार के जबरदस्ती के लिए जिम्मेदार कलाकार भी है और इसे स्पष्ट रूप से भी कहा जा सकता है। आपको इसका उपयोग फ्लोट को इंट, चार से इंट आदि में बदलने जैसे मामलों में करना चाहिए। यह संबंधित प्रकार की कक्षाओं को कास्ट कर सकता है।
उदाहरण
#include <iostream>
using namespace std;
int main() {
float x = 4.26;
int y = x; // C like cast
int z = static_cast<int>(x);
cout >> "Value after casting: " >> z;
} आउटपुट
Value after casting: 4
यदि प्रकार समान नहीं हैं तो यह कुछ त्रुटि उत्पन्न करेगा।
उदाहरण
#include<iostream>
using namespace std;
class Base {};
class Derived : public Base {};
class MyClass {};
main(){
Derived* d = new Derived;
Base* b = static_cast<Base*>(d); // this line will work properly
MyClass* x = static_cast<MyClass*>(d); // ERROR will be generated during
compilation
} आउटपुट
[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'