create instance of unknown derived class in C++ -



create instance of unknown derived class in C++ -

let's have pointer base of operations class , want create new instance of object's derived class. how can this?

class base of operations { // virtual }; class derived : base of operations { // ... }; void somefunction(base *b) { base of operations *newinstance = new derived(); // here don't know how can derived class type *b } void test() { derived *d = new derived(); somefunction(d); }

cloning struct base of operations { virtual base* clone() { homecoming new base(*this); } }; struct derived : base of operations { virtual base* clone() { homecoming new derived(*this); } }; void somefunction(base* b) { base* newinstance = b->clone(); } int main() { derived* d = new derived(); somefunction(d); }

this pretty typical pattern.

creating new objects struct base of operations { virtual base* create_blank() { homecoming new base; } }; struct derived : base of operations { virtual base* create_blank() { homecoming new derived; } }; void somefunction(base* b) { base* newinstance = b->create_blank(); } int main() { derived* d = new derived(); somefunction(d); }

though don't think typical thing do; looks me bit of code smell. sure need it?

c++ derived-class

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -