Is there a fast (and unsafe) way to downcast pointers without checking?

230 Views Asked by At

I want to downcast a base class pointer to a derived class pointer.

I know that dynamic cast is costly so I want to avoid it. In my case, I am fully aware of the actual class the pointer in question points to. Is there a faster way to downcast it than dynamic casting?

I tried to use static_cast but it won't apply here, because there is virtual inheritance in my class hierarchy.

Update:

Thanks for the comments, I now realize that those dynamic cast is not likely to be the bottleneck of the whole program so it is almost a waste of time trying to optimize it.

2

There are 2 best solutions below

1
Sam Varshavchik On

It does seem that this is exactly what virtual methods are for. Appropriate use of virtual methods eliminates most needs of dynamic casting. And it even works with virtual inheritance.

#include <stdexcept>
#include <iostream>

class Derived;

class Base {

public:
    virtual Derived *to_derived()
    {
        throw std::runtime_error("Nope");
    }
};

class Derived : virtual public Base {
public:
    Derived *to_derived() override
    {
        return this;
    }
};

class DerivedAgain : public Derived
{
};

int main()
{
    DerivedAgain kit_and_kaboodle;

    Base *p=&kit_and_kaboodle;


    std::cout << (p->to_derived() ? "it works\n":"no it doesn't\n");
    return 0;
}

Add a const overload, for const-correctness, if needed.

0
HerrJoebob On

reinterpret_cast<> is the answer to the basic question of what will downcast without any dynamic checks. It's the strongest (i.e. least-safe) cast this side of a C-style cast.