2

I have a method which returns pointer of one of three relative classes:

Base* Base::search_by_name(string name) { children_iterator = children.begin(); while (children_iterator != children.end()) { if (name == (*children_iterator)->getName()) { switch ((*children_iterator)->class_number) { case 1: return ((Derived*)*children_iterator); case 2: return ((Derived2*)*children_iterator); case 3: return ((Derived3*)*children_iterator); } 

And I need to create an object exactly of the class, which class` pointer method returns

 bool Base::set_connection(int number, string& process_object) { typeid(root->search_by_name(process_object)) myobject; // Derived myobject, Derived2 myobject or Derived3 myobject if (myobject != NULL) { string signal = this->getName(); myobject->get_connection (number, signal); //each class has its own realisation of get_connection 

I tryed the line typeid(root->search_by_name(process_object)) myobject;But it`s obviously silly. Could you advise something?

1
  • You can try using a void pointer and later typecast it accordingly. Not a clean solution though. Commented May 8, 2021 at 21:22

1 Answer 1

2

It's not possible to derive the static type of the polymorphic object so as to make a static declaration of type as in:

my_static_type object; 

There are a couple of things you could do.

One is to put a clone() or create() style function in your polymorphic classes to return correctly typed dynamic objects.

BaseClass* n = root->search_by_name(process_object)->create(); // new object 

The other would be to manually query the possible types, which rather defeats the point of polymorphism:

auto* p = root->search_by_name(process_object); BaseClass* b; if(auto* n = dynamic_cast<Derived*>(p)) b = new Derived; else if(auto* n = dynamic_cast<Derived2*>(p)) b = new Derived2; else throw std::runtime_error("problems problems"); 

NOTE: Pointers used for exposition only, use std::unique_ptr etc.. in real code.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.