mercredi 26 décembre 2018

c++ dynamic return type for function

I am trying to have a generic class which could return the object of the other class depending on the input to generic class.

From the main function, if I pass in '1' as an argument to the constructor of generic class, i want to be able to get object of child1 class using getType(). My question is: is there a way to change the return type of getType() dynamically or any other way to accomplish this behavior?

My current implementation calls the print() method of base class, even though I create an object of child classes in generic constructor as m_type is a base type.

class base {

    public:
        void print(){
            cout << "base\n";
        }
        virtual ~base() {}
};

class child1 : public base {
    public:
        void print(){
            cout << "child1\n";
        }
};

class child2 : public base {
    public:
        void print(){
            cout << "child2\n";
        }
        void hello(){
            cout << "hello from child 2\n";
        }
};

class generic{

    public:
        generic(int b){
            if(b==1) {
                m_type = new child1();
            }
            else if(b==2) 
                m_type = new child2();
        }

    // Somehow return the object of one of the child class based on input 
    // to constructor.
    base *getType(){
        return m_type;
    }

    base *m_type;
};

int main()
{
    generic *g1 = new generic(1);
    // call the method from child1 class instead of base class.
    g1->getType()->print();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire