let's say I have a pointer to some base class and I want to create a new instance of this object's derived class. How can I do this?
class Base
{
// virtual
};
class Derived : Base
{
// ...
};
void someFunction(Base *b)
{
Base *newInstance = new Derived(); // but here I don't know how I can get the Derived class type from *b
}
void test()
{
Derived *d = new Derived();
someFunction(d);
}
struct Base {
virtual Base* clone() { return new Base(*this); }
};
struct Derived : Base {
virtual Base* clone() { return new Derived(*this); }
};
void someFunction(Base* b) {
Base* newInstance = b->clone();
}
int main() {
Derived* d = new Derived();
someFunction(d);
}
This is a pretty typical pattern.
struct Base {
virtual Base* create_blank() { return new Base; }
};
struct Derived : Base {
virtual Base* create_blank() { return new Derived; }
};
void someFunction(Base* b) {
Base* newInstance = b->create_blank();
}
int main() {
Derived* d = new Derived();
someFunction(d);
}
Though I don't think that this a typical thing to do; it looks to me like a bit of a code smell. Are you sure that you need it?
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