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 objectsstruct 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
Post a Comment