6

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

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

Remember default is to be private unless you specify otherwise just like member variables

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.