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 <iostream>
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;
}
You're looking for a variant
type. There's an upcoming std::variant
in C++17, and C++11-compliant versions in boost
and around the web. Example with boost::variant:
struct visitor
{
void operator()(const A&){ cout << "HELLO A" << endl; }
void operator()(const B&){ cout << "HELLO B" << endl; }
void operator()(const C&){ cout << "HELLO C" << endl; }
};
int main()
{
visitor v;
// `obj` is either an `A`, a `B` or a `C` at any given moment.
boost::variant<A, B, C> obj{B{}};
// ^^^^^
// Initialize with `B`.
boost::apply_visitor(v, obj); // prints "HELLO B"
obj = A{};
boost::apply_visitor(v, obj); // prints "HELLO A"
}
you could do something like
if (key == "a") obj=new A();
else if (key == "b") obj=new B();