Search code examples
c++polymorphismdynamic-caststatic-cast

Use static_cast to dynamic polymorphism


I used a static_cast to polymorphism. I read that I should use dynamic_cast, but I can't get why. Code works in both way (with static and dynamic cast).

Could anybody show me an example with necessary dynamic_cast operator?

class Base
{
    public:
    virtual void foo() = 0;
};

class D1 : public Base
{
    public:
    void foo()
    {
        std::cout << "D1()";   
    }
};

class D2 : public Base
{
    public:
    void foo()
    {
        std::cout << "D2()";   
    }
};


int main()
{
    srand( time( NULL ) );
    int r = std::rand()%2;

    Base* b_ptr;

    if(r == 0)
    {
        b_ptr = static_cast<Base*>(new D1);    
    }
    else
    {
          b_ptr = static_cast<Base*>(new D2);   
    }

    b_ptr->foo();
}

Solution

  • I don't know where you read what you read. As for static_cast vs. dynamic_cast, there is plenty of information out there. I am providing a couple of links at the bottom.

    Why your code works in any of the two cases?
    An "up-cast" (cast to the base class) is always valid with both static_cast and dynamic_cast, and also without any cast, as an "up-cast" is an implicit conversion. (from here, e.g.)

    Could anybody show me an example with necessary dynamic_cast operator?
    dynamic_cast is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. The dynamic_cast will seek out the desired object and return it if possible. If it can't, it will return nullptr in the case of a pointer, or throw std::bad_cast in the case of a reference.
    dynamic_cast has some limitations, though. It doesn't work if there are multiple objects of the same type in the inheritance hierarchy (the so-called 'dreaded diamond') and you aren't using virtual inheritance. It also can only go through public inheritance - it will always fail to travel through protected or private inheritance. This is rarely an issue, however, as such forms of inheritance are rare. (from here, e.g.)
    For an example, see this.

    Bonus: When you cannot use dynamic_cast?
    You cannot use dynamic_cast if you downcast (cast to a derived class) and the argument type is not polymorphic.

    Regular cast vs. static_cast vs. dynamic_cast

    When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?