c++static-cast

static_cast - Why is it working here?


I have the following code snippet

class base
{
public:
    virtual void MyMethod()
    {
        std::cout << "Base MyMethod" << "\n";
    }
};


class der : public base
{
public:
    virtual void MyMethod()
    {
        std::cout << "Derived MyMethod" << "\n";
    }
};


void foo(base* b)
{
    der* d = static_cast<der*>(b);
    d->MyMethod();
}

int main()
{
    base* b = new der();
    foo(b);
}

Now my question is why is static_Cast working here. I read that static_casts cannot cast through polymorphic types. so why is the above example working - Am I missing something here ? I was expecting that dynamic cast could only resolve such an issue since they should be used with polymorphic types ? Could anyone give an example where static cast would fail and dynamic cast would pass ?


Solution

  • “Now my question is why is static_cast working here.”

    There is no reason why it should not work. The types are related by class derivation, and that’s known by the compiler. Essentially static_cast is restricted to do or undo any implicit conversion, and you do have an implicit conversion from der* to base*.

    “I read that static_casts cannot cast through polymorphic types.”

    That’s just balderdash.

    “[snip] Could anyone give an example where static cast would fail and dynamic cast would pass?”

    struct A { virtual ~A(){} };
    struct B { virtual ~B(){} };
    
    struct T: A, B {};
    
    auto main()
        -> int
    {
        T o;
        A& oA = o;
        //B& oB = static_cast<B&>( oA );    //! This won't compile, unrelated types.
        B& oB = dynamic_cast<B&>( oA );
    }