Question

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 ?

Was it helpful?

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 );
}

OTHER TIPS

Usually dynamic_cast is used, to cast a base pointer to a derived pointer. This is because the object pointed to by base, may not actually be the derived type. So dynamic_cast performs a run-time check, and returns a null pointer if the object is incompatible.

But this run-time check has a slight performance cost. If you are totally sure in the logic of your program, that the cast will succeed, you can use a static_cast instead and prevent the run-time check. But if you get the object type wrong, you will get undefined behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top