What is the difference between regular cast, static_cast and dynamic_cast in C++?
Hello colleagues! I'm learning C++ and I'm confused about type casts. Textbooks often say: "avoid C-style cast" but don't explain why. I'm writing a simple class hierarchy: there's a base class `Shape` and derived classes `Circle` and `Rectangle`. When I try to convert a pointer from `Shape*` to `Circle*`, I use a regular C-style cast: `(Circle*)shape_ptr`. It seems to work, but sometimes the compiler complains or the program crashes. Then I learned about `static_cast` and `dynamic_cast`.
Here's an example that confuses me:
```cpp
class Shape { public: virtual ~Shape() {} };
class Circle : public Shape { public: void drawCircle() { /* ... */ } };
class Rectangle : public Shape { public: void drawRect() { /* ... */ } };
void process(Shape* s) {
// Option 1: C-style cast
Circle* c1 = (Cir
No answers yet.
Log in to leave an answer