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
It seems to me that you should use a virtual common base class/struct and a pointer to this base class/struct.
The following is a full working example
#include
struct Base
{ virtual void printHello () = 0; };
class A : public Base {
public:
void printHello() { std::cout << "HELLO A" << std::endl; }
};
class B : public Base{
public:
void printHello() { std::cout << "HELLO B" << std::endl; }
};
class C : public Base{
public:
void printHello() { std::cout << "HELLO C" << std::endl; }
};
int main () {
std::string key = "c";
A a;
B b;
C c;
Base * obj;
if (key == "a") obj = &a;
else if (key == "b") obj = &b;
else obj = &c;
obj->printHello(); // print Hello C.
return 0;
}