Avatar ·

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

Hello! I've just started learning C++ and I can't figure out type casting. It seems there are four different operators: static_cast, dynamic_cast, const_cast and reinterpret_cast. But when to use which — it's a complete mess.\n\nFor example, I want to convert a double to an int. Can't I just write (int)value, like in C? Why do I need static_cast?\n\nOr here's a situation: I have a class hierarchy, and I want to convert a pointer to a base class into a pointer to a derived class. I've heard that dynamic_cast is used for this, but it only works with virtual functions. What if there are none? Can I use static_cast?\n\nAlso, const_cast confuses me. I know it can "remove" constness. But isn't that dangerous? And why would you ever need to modify a const object?\n\nAnd the scariest