Reputation: 81
How to initialize object dynamically in the program without inheritance in c++? For example i Have class A and class B. And depend on condition i need to create instance of object but i don't know exactly what object i need to create, it depends on information that user input;
Example code:
int i;
cin>>i>>endl;
void *obj;
if(i)
obj = new A();
else
obj = new B();
Upvotes: 1
Views: 182
Reputation: 1130
You can use std::any or std::variant depending on your needs.
Casting a pointer to void*
is (most of the time) a bad idea because you loose the type of the object and you have to deal with raw pointer. Which means that you have to manage resources, call the right destructor... any
and variant
do that for you.
I would recommend using variant
and not any
, unless you have a specific need for any
because variant
give you more control over the type: your value can have only a limited list of type.
Upvotes: 1
Reputation: 261
If you do not have limitation of taking pointers then take two pointers of both classes and initialize the one according to input.
int i;
A *a_ptr;
B *b_ptr;
cin>>i>>endl;
if(i)
a_ptr = new A();
else
b_ptr = new B();
Upvotes: 1