Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Object creating new instances of same type

Is there a way to give an object the possibility to create new objects of it's own type, without specifying this type?

class Foo {
public:
    virtual Foo* new_instance() {
        return new type_of(this); // Some magic here
    }
};

class Bar: public Foo {

};

Foo* a = new Foo();
Foo* b = new Bar();
Foo* c = a->new_instance();
Foo* d = b->new_instance();

I would now like c to be of type Foo, while d should be of type Bar.

like image 648
Magnar Myrtveit Avatar asked Feb 13 '23 06:02

Magnar Myrtveit


2 Answers

Short answer: No, there is no way to make this magic happen.

You could use a macro to make overriding the function in subclasses easier, or create an intermediate class that uses the "curiously recurring template pattern":

template <typename T>
class FooDerived : public Foo
{
public:
    T* new_instance() {
        return new T();
    }
};

class Bar : public FooDerived<Bar>
{
};

Foo* a = new Bar();
Foo* b = a->new_instance(); // b is of type Bar*

But this is most certainly not worth the effort.

like image 193
Ferdinand Beyer Avatar answered Feb 19 '23 23:02

Ferdinand Beyer


Straightforward solution:

class Foo {
public:
    virtual Foo* new_instance() {
        return new Foo();
    }
};

class Bar: public Foo {
public:
    virtual Foo* new_instance() {
        return new Bar();
    }
};
like image 43
qehgt Avatar answered Feb 19 '23 23:02

qehgt