Avatar ·

When to use static_cast, dynamic_cast, const_cast and reinterpret_cast in C++?

Hello everyone! I started learning C++ and came across different type casting operators. I know that in C there is simple cast in parentheses, but they say that in C++ you need to use special operators: `static_cast`, `dynamic_cast`, `const_cast` and `reinterpret_cast`. I'm completely confused about when to use which.\n\nFor example, I have this code:\n\n```cpp\nclass Base {\npublic:\n virtual void show() { std::cout << "Base"; }\n};\n\nclass Derived : public Base {\npublic:\n void show() override { std::cout << "Derived"; }\n void extra() { std::cout << "Extra"; }\n};\n\nint main() {\n Base* basePtr = new Derived();\n \n // How to correctly cast Base* to Derived*?\n Derived* d1 = (Derived*)basePtr; // C-style cast — it works, but is it correct?\n \n int a = 10;\n d