开发者

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(); // b开发者_运维技巧ut here I don't know how I can get the Derived class type from *b
}

void test()
{
    Derived *d = new Derived();
    someFunction(d);
}


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?


It's called clone and you implement a virtual function that returns a pointer to a dynamically-allocated copy of the object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜