I know about the existence of static_cast, dynamic_cast. But I can’t seem to find out a concrete reason to convince myself about why cast from base to derive or vice versa?
Any example in code would be appreciated.
UPDATE
class Base
{
public:
void foo();
private:
int _x;
};
class Derive: Base
{
};
Base *b = new Derive; //will b behave the same as if it's a Derive *?
Derive *d = new Base; //I think d can't behave like a Derive * but Base *, right?
Actually, those casts are obvious marks of something unsual going on in the code, so in a perfect world, you shouldn’t use them.
But in some cases they are the right tool for the job.
For static_cast, there are basically 2 cases:
1. Primitive conversion.
When you really need some integer number to be processed in a calculus involving floats.
2. You got an object from some external API and you want to get the specific child-type.
If you designed the system, maybe you could have done it better to avoid the cast. But if you didn’t and the API you’re using provide the base type as a way for you to work with it, then you don’t have any other choice than to cast.
static_cast is useful also because it lets you assume something at compile time, so you should use it first because it requires you to be sure about what you are doing.
3.You don’t know what is the real type of the object.
However, there is a specific case when you need to know the real type at runtime because there is no way for you to know it at another time. Typical case is when you’re receiving some kind of objects from an external system and there is no other information about the real type of the object