Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ dynamic_cast with multiple inheritance

Is possible to get object through dynamic_cast using multiple-inheritance ? I prefer to skip compositional trick due to designing issue I have. Thanks,

#include <stdio.h>

namespace
{
    template <typename T>
    class Beta
    {
    protected:
        Beta() { printf("Beta\n"); }
    public:
        virtual ~Beta() { printf("~Beta\n"); }
        virtual void Run() = 0;

    };

    class Alpha
    {
    protected:
        Alpha() { printf("Alpha\n"); }
    public:
        virtual ~Alpha() { printf("~Alpha\n"); }
        virtual void Check() = 0;

        template <typename T>
        Beta<T>* GetBeta()
        {
            Beta<T>* b = dynamic_cast< Beta<T>* >(this);

            if(b == NULL) printf("NULL !!\n");

            return b;
        }
    };

    template <typename T>
    class Theta : public Alpha, Beta<T>
    {
    public:

        void Run()
        {
            printf("Run !\n");
        }

        void Check()
        {
            printf("Check !\n");
        }

    };
}

int main(int argc, const char* argv[])
{
    Alpha* alpha = new Theta<int>();
    Beta<int>* beta = alpha->GetBeta<int>();

    alpha->Check();

    if(beta) beta->Run();

    delete alpha;
    return 0;
}

The result from above code is

Alpha Beta NULL !! Check ! ~Beta ~Alpha

like image 633
user2792318 Avatar asked Sep 18 '13 16:09

user2792318


People also ask

Is Static_cast faster than dynamic_cast?

While typeid + static_cast is faster than dynamic_cast , not having to switch on the runtime type of the object is faster than any of them. Save this answer.

Is dynamic_cast a code smell?

Yes, dynamic_cast is a code smell, but so is adding functions that try to make it look like you have a good polymorphic interface but are actually equal to a dynamic_cast i.e. stuff like can_put_on_board .

Is dynamic_cast fast?

dynamic_cast runs at about 14.4953 nanoseconds. Checking a virtual method and static_cast ing runs at about twice the speed, 6.55936 nanoseconds.

Does dynamic_cast use RTTI?

For example, dynamic_cast uses RTTI and the following program fails with the error “cannot dynamic_cast `b' (of type `class B*') to type `class D*' (source type is not polymorphic) ” because there is no virtual function in the base class B.


1 Answers

Well, if I replace:

public Alpha, Beta<T>

with:

public Alpha, public Beta<T>

Things will work. There is always a devil in the details...

like image 192
user2792318 Avatar answered Oct 23 '22 07:10

user2792318