Safe cast to derived class

Hi,

I want to cast a base-class-pointer to a derived-class-pointer in the following fashion:

1
2
3
4
5
void myfunction(Base* base) {
    if(typeid(base) == typeid(Derived*) {
        dynamic_cast<Derived*>(base)->derivedSpecificMethod();
    }
}


It compiles fine but ensures this usage of typeid that the cast is successful and the call of derivedSpecificMethod is safe? Is there a better method to do this?

Thanks!
Last edited on
When used with a pointer, dynamic_cast<> returns a null pointer if the cast fails. So you can use it like this.

1
2
3
4
5
void myfunction(Base* base) {
    Derived* derived = dynamic_cast<Derived*>(base);
    if(derived)
        derived->derivedSpecificMethod();
}


Andy
Topic archived. No new replies allowed.