// Define an Item class with a name and quantity class Item { public: std::string name; int quantity; Item(std::string name, int quantity) : name(name), quantity(quantity) {} Item CloneItem() { return Item(name, quantity); } }; // Creating an item and cloning it Item apple("Apple", 5); Item apple_copy = apple.CloneItem(); // Clone the apple item apple_copy.quantity = 2; // Change the quantity of the copy std::cout << apple.quantity << std::endl; // Output: 5 std::cout << apple_copy.quantity << std::endl; // Output: 2
// Define an Item class with a name, quantity, and a pointer to an int class Item { public: std::string name; int quantity; int* ptr; Item(std::string name, int quantity, int* ptr) : name(name), quantity(quantity), ptr(ptr) {} Item CloneItem() { return Item(name, quantity, ptr); } }; // Creating an item with a pointer and cloning it int* ptr = new int(10); Item item("Name", 5, ptr); Item item_copy = item.CloneItem(); // Clone the item *(item_copy.ptr) = 20; // Change the value of the pointer in the copy std::cout << *(item.ptr) << std::endl; // Output: 20 std::cout << *(item_copy.ptr) << std::endl; // Output: 20In this example, we create an Item class with a name, quantity, and a pointer to an int. We define a function, CloneItem(), that creates a clone of the object it is called on. We then create an item object with a pointer and clone it to create a copy called item_copy. Finally, we change the value of the pointer in the copy and print out the original and copy values to verify that they are separate objects. Package library: Standard library