简体   繁体   中英

Copy constructor-like copying of base class instance in the derived class

I have an unusual problem in a large system where for various reasons I might have to use a construct like this:

class Item
{
    int mID;
    int mID2;
    ...
    int mIDn;

public:
    Item();
    Item(const Item& Other);
    Item& operator=(const Item &Other);
};

class ItemExtension : public Item
{
     // some data
public:
     ItemExtension(const Item &Other) : Item(Other) {}
     ItemExtension(const ItemExtension &Other);
     ItemExtension& operator=(const ItemExtension& Other);
};


// client code
Item *Myitem = ItemList.ReleaseItem(index); // ownership transferred and an Item is removed from a list

std::auto_ptr<ItemExtension> ItemExt(new ItemExtension(*MyItem));
ItemExtList.push_back(ItemExt.release()); // store in std::vector and take ownership

I realize there are design flaws here, such as the chaotic transfers of pointer ownership, but is it considered really bad form to initialize a derived class object with a base class version if the data you need to copy is predominantly contained in the base class, but you need specific functionality that is only supported in the derived class? Thanks a lot.

With this design you get "sideways-conversion" in your class hierarchy, eg

void foo(ItemExtension const&)

class OtherItemExtension: public Item { /* ... */ };
OtherItemExtenstion bar;

foo(bar);

Here the call to foo succeeds by creating a temporary ItemExtension from bar and passing that to foo . Most likely that is not what you want.

Note that even if you make the constructor explicit, the following will still succeed:

ItemExtension baz(bar);

You most likely don't want that, making it a bad idea to have that constructor.

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