Casting
Static Cast
A static cast allows casts whose types are compatible. It will catch const type casting errors at compile time.File: static1.cpp
#include <iostream> using namespace std ; int main() { int x1 = 10; float f1 = 10.5 ; x1 = static_cast<int>(f1); cout << "x1:" << x1 << endl ; //Undefined behavior //Not recommended const int x2 = 11 ; int* ptr1 = static_cast<int*>(&x2) ; *ptr1 = 12 ; cout << "x2:" << x2 << endl ; } $ rm a.exe ; g++ static1.cpp ; ./a.exe static1.cpp: In function ‘int main()’: static1.cpp:15:18: error: invalid ‘static_cast’ from type ‘const int*’ to type ‘int*’ 15 | int* ptr1 = static_cast(&x2) ; | ^~~~~~~~~~~~~~~~~~~~~~ bash: ./a.exe: No such file or directory The "static_cast" catches the const cast issue. However it allows wrong inheritance casting.
File: static2.cpp
#include <iostream> using namespace std ; class A { public: int x1 ; }; class B : public A { public: int x1B ; }; class C : public A { public: int x1C ; }; int main() { int x1 = 10; float f1 = 10.5 ; x1 = static_cast<int>(f1); cout << "x1:" << x1 << endl ; B bObject ; bObject.x1B = 22 ; A* aObject = &bObject ; //Not valid as aObject contains bObject as the //underlying object C* cObject = static_cast<C*> (aObject) ; cout << cObject->x1C << endl ; } $ rm a.exe ; g++ static2.cpp ; ./a.exe x1:10 22 We notice that static_cast did not give us any compile time or run time errors. For this type of inheritance based casting we should use dynamic casting.