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
.
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.
Straightforward solution:
class Foo {
public:
virtual Foo* new_instance() {
return new Foo();
}
};
class Bar: public Foo {
public:
virtual Foo* new_instance() {
return new Bar();
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With