C++ How to avoid Object Slicing with derived classes being stored in base vector | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C++ How to avoid Object Slicing with derived classes being stored in base vector

Hey everyone, I am not sure if this is elegant, but I want to store multiple derived classes in a base vector but I don’t want my objects to get sliced. I can’t figure this out. For example, let’s say I have a base class “Item” and derived classes “Weapon” or “Armor”. I want to store the derived classes in a “vector<Item*> “ but the object get sliced to the base class. Can anyone assist me here? Maybe creating a copy constructor would fix this?

10th Apr 2020, 4:22 PM
Tyler
Tyler  - avatar
4 Answers
+ 4
Object will get sliced only if you store it in vector as object, like vector<Item> If you store a pointer to an object in vector like vector<Item*> then the object will not get sliced. Use dynamic_cast for safe casting to derived class like weapon = dynamic_cast<Weapon*>(v[i]) Also you can replace pointer to Item (Item*) with shared_ptr<Item>
10th Apr 2020, 5:33 PM
andriy kan
andriy kan - avatar
+ 4
In your code object is not sliced. You just don't override getClass() method. Also getName() is not defined in class A You should declare class A as folow class A { public: virtual void getClass() { cout << "A"; } virtual void getName(){} };
10th Apr 2020, 5:36 PM
andriy kan
andriy kan - avatar
+ 1
andriy kan Thank you for your response. This was the explanation that I needed. I searched through many different sources and I became confused. Making the methods virtual was the key. I assumed that the objects were being sliced but that wasnt the case. Thanks again
10th Apr 2020, 7:51 PM
Tyler
Tyler  - avatar
0
Here is an example, is there a solution to this or will i have to come up with a different data structure? I am not sure what i am missing. https://code.sololearn.com/cW9fA8XP4iaP/?ref=app
10th Apr 2020, 5:26 PM
Tyler
Tyler  - avatar