mercredi 29 mars 2017

Create a variable to hold objects of different types C++

I have 3 different objects A, B and C. Depending on the the parameter given, I would like to choose among these different objects. In programming,

class A { 
  public: 
    void printHello() { cout << "HELLO A" << endl; }
}; 

class B { 
  public: 
    void printHello() { cout << "HELLO B" << endl; }  
};

class C { 
   public: 
     void printHello() { cout << "HELLO C" << endl; }  
}; 

int main () { 
    string key = "c"; 
    A a; 
    B b; 
    C c; 
    Object obj; // I don't know how to declare Object. 

    if (key == "a") obj = a; 
    else if (key == "b") obj = b; 
    else obj = c;
    obj.printHello(); // print Hello C.
    return 0; 
} 

I have thought about templates and struct objects. But none of them work so far.

template<typename T1, T2, T3> 
T1 getType(string key, T1 t1, T2 t2, T3 t3) { // this is problem coz return types are different.
    if (key == "a") return t1; 
    else if (key == "b") return t2; 
    else return t3; 
} 

It is easy to create Object o; in JAVA because every object in Java is subclass of Object class. But how do I achieve this in C++?

Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire