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();
5
  • Possible duplicate of Casting Class Pointer to Void Pointer Commented Jun 22, 2017 at 8: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. Commented Jun 22, 2017 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? Commented Jun 22, 2017 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. Commented Jun 22, 2017 at 11:50
  • If you don't like dynamic polymorphism, then static polymorphism with templates might suit you better. Commented Jun 22, 2017 at 11:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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();

1 Comment

i know that, but may i create only one pointer and initialize object that i need?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.