static_cast का उपयोग सामान्य/साधारण प्रकार रूपांतरण के लिए किया जाता है। यह निहित प्रकार जबरदस्ती (implicit type coercion) के लिए भी जिम्मेदार कास्ट है और इसे स्पष्ट रूप से भी बुलाया जा सकता है। आपको इसका उपयोग फ्लोट को इंट में, चार को इंट में आदि जैसे मामलों में करना चाहिए। यह संबंधित प्रकार के क्लासेस को कास्ट कर सकता है।
उदाहरण
#include <iostream>
using namespace std;
int main() {
float x = 4.26;
int y = x; // C जैसा कास्ट
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); // यह लाइन ठीक से काम करेगी
MyClass* x = static_cast<MyClass*>(d); // संकलन के दौरान त्रुटि उत्पन्न होगी
}
आउटपुट
[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'