简体   繁体   中英

C++ Copying objects with polymorphism

I want to copy objects in c++. The problem is that i have derived classes with polymorphism, as shown i the pseudocode below:

class BaseCl { some virtual functions };
class DerivedClass : public BaseCl { ... };

...

BaseCl * b1 = new DerivedClass();
BaseCl * b2 = new "copy of b1"; (just pseudocode)

The problem is the last line:

I want to copy an object of the class "BaseCl", but because of the polymorphism the copy must be just like the original object of "DerivedClass".

What is the best way to do that?

Thank you very much, any help is appreciated.

Edit: Problem has been solved:

Inserted:

virtual BaseCl *clone() = 0;

in the base class and

DerivedCl *clone() {return new DerivedCl(*this);}

in the derived class. Thank you all.

You need to define a function in BaseC1 that makes a clone. Something like:

class BaseCl
{
    virtual BaseCl* clone() {return new BaseC1(*this);}
};
class DerivedClass : public BaseCl
{
    virtual BaseCl* clone() {return new DerivedClass(*this);}
};

The key of runtime polymorphism is that operations must be implemented in the most derived object, since it is the one than know everything it has to be known to perform them. All bases must expose virtual functions to be called by base pointers.

You can devine at the base level a virtual BaseCl* clone() function, and override it your derived classes to return new DerivedClass(*this)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM