Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create instance of unknown derived class in C++

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);
}
like image 744
Ben Avatar asked Jul 08 '11 14:07

Ben


1 Answers

Cloning

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.


Creating new objects

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?

like image 74
Lightness Races in Orbit Avatar answered Sep 21 '22 05:09

Lightness Races in Orbit