Cloning an object
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15

Thread: Cloning an object

Threaded View

  1. #1
    Join Date
    Apr 2013
    Posts
    33

    Cloning an object

    Is there a point in dynamically creating a pointer during runtime only to dereference it? (if that is the right term, as in *pointer, depoint it?)
    In this case should I perhaps store pointers instead of references?

    Inventory.cpp


    Code:
    bool Inventory::addItem(InventoryItem& item)
    {
    	addItemAmount(item);
    
    	if (item.getAmount() > 0) {
    		if (hasEmptySlot()) {
    			addNewItem(*item.clone());
    			return true;
    		}
    		else return false;
    	}
    
    	return true;
    }
    
    void Inventory::addNewItem(InventoryItem& item)
    {
    	array.push_back(item);
    }
    InventoryItem.cpp

    Code:
    std::unique_ptr<InventoryItem> InventoryItem::clone(void) const
    {
    	return std::unique_ptr<InventoryItem>(new InventoryItem(index, name, type, maxAmount));
    }
    Also I was wondering, is there some sort of built-in cloning functionality or do I have to write the clone functions myself? When creating new instances I see that I can either pass the constructor properties or a reference to an object of the same type.

    For instance:

    Code:
    new InventoryItem(index, name....);
    new InventoryItem(const InventoryItem&);
    Is the second one casting?
    Last edited by royibernthal; April 8th, 2013 at 08:08 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center