user2792318
user2792318

Reputation: 141

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

Upvotes: 6

Views: 2023

Answers (1)

user2792318
user2792318

Reputation: 141

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...

Upvotes: 8

Related Questions