1

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();
Cœur
  • 37,241
  • 25
  • 195
  • 267
icegas
  • 71
  • 1
  • 1
  • 9
  • Possible duplicate of [Casting Class Pointer to Void Pointer](https://stackoverflow.com/questions/18929225/casting-class-pointer-to-void-pointer) – Tryum Jun 22 '17 at 08:13
  • Why do you want to avoid inheritance? If you need to be able to store either of the two classes in one variable, then classes have to have something in common. If they have something in common, then inheritance is natural solution. – el.pescado - нет войне Jun 22 '17 at 10:21
  • it only one way? but if i have class of matrix and class of Vector? Do you think that it good choice first of all create abstract class? – icegas Jun 22 '17 at 11:03
  • You have two paths in your code. One for Vector and one for Matrix. You want to have a variable which is capable of holding either of the two, so I assume those two code paths join later in, i.e. there's some `do_something_with_either_matrix_or_vector(obj);` function call. That means both Vector and Matrix share some properties, which in turn means that yes, abstract class (think interface in java/c#) would be good fit. – el.pescado - нет войне Jun 22 '17 at 11:50
  • If you don't like dynamic polymorphism, then static polymorphism with templates might suit you better. – el.pescado - нет войне Jun 22 '17 at 11:52

2 Answers2

1

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();
Manish Sogi
  • 201
  • 2
  • 7
1

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 variantgive you more control over the type: your value can have only a limited list of type.

nefas
  • 1,120
  • 7
  • 16