Cognosce
Cognosce

Reputation: 63

Dynamically create on object of type C++

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?

Upvotes: 2

Views: 84

Answers (1)

Galik
Galik

Reputation: 48605

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.

Upvotes: 2

Related Questions