CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Threaded View

  1. #1
    Join Date
    Jan 2010
    Posts
    10

    Multiple virtuality

    Is it possible to make a virtual function behave differently based on the data it is given even if the latter is an abstract pointer and how?

    I tried making something like that, the function calls look good enough, but the implementation is simplistic. I'd rather not have a switch statement in every concrete class derived form BaseB.



    Code:
    #include <iostream>
    
    
    using namespace std;
    
    class BaseA
    {
        public:
        virtual char getType()=0;
    
    };
    
    class A1:public BaseA
    {
        public:
        char getType()
        {
            return 'a';
        }
    };
    
    class A2:public BaseA
    {
        public:
        char getType()
        {
            return 'b';
        }
    
    };
    
    class BaseB
    {
        public:
        virtual void use(BaseA*)=0;
    };
    
    
    
    class B1:public BaseB
    {
        public:
    
        void use(BaseA* basea)
        {
            switch(basea->getType())
            {
                case 'a':
                handle((A1*)basea);
                break;
                case 'b':
                handle((A2*)basea);
                break;
                default:
                break;
            }
        }
        void handle(A1* a1)
        {
            cout<<"B1 uses A1"<<endl;
        }
        void handle(A2* a2)
        {
            cout<<"B1 uses A2"<<endl;
        }
    };
    
    class B2:public BaseB
    {
        public:
        void use(BaseA* basea)
        {
            switch(basea->getType())
            {
                case 'a':
                handle((A1*)basea);
                break;
                default:
                break;
            }
        }
        void handle(A1* a1)
        {
            cout<<"B2 uses A1"<<endl;
        }
        void handle(A2* a2)
        {
            cout<<"B2 uses A2"<<endl;
        }
    };
    
    int main()
    {
    
        BaseA* baseA[2]={new A1, new A2};
        BaseB* baseB[2]={new B1, new B2};
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                baseB[i]->use(baseA[j]);
    
        return 0;
    }
    Last edited by wasd; February 9th, 2011 at 03:03 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured