2

I have a linked list of type Device:

Node<Device> list = new Node<device>(device);

And Device have derived classes:

enter image description here

And I need my list to be able to hold every derived class of Device.

How can I do it?

Note: If I send an Aerobic_Device to the list, it just dynamically converts to Device, which loses data.

EDIT:

I changed all the logic of my program to work with pointers, and now the list is: Node<Device*> - Which still converts everything to Device type. Now, as many suggested, I switched it to Node<std::unique_ptr<Device>>, but this just introduced many many many errors.

Community
  • 1
  • 1
Amit
  • 5,924
  • 7
  • 46
  • 94

2 Answers2

2

You cannot store your objects by value and have polymorphic behavior at the same time. You can store your objects by (preferably smart) pointer:

Node<std::unique_ptr<Device>> list;
1

Make the list to be of type Device* (note the pointer).

Node<Device*> list;

Then, declare objects of derived types (PowerDevice, AerobicDevice, PowerAerobicDevice) and put them in the list.

This way you can leverage the power of runtime polymorphism.

Alternatively, you can (and should) use smart pointers instead of raw pointers to automatically handle the memory:

std::unique_ptr<Device> pDevice= std::make_unique<PowerDevice>(...);
// put into list
std::unique_ptr<Device> aDevice= std::make_unique<AerobicDevice>(...);
// put into list
std::unique_ptr<Device> paDevice= std::make_unique<PowerAerobicDevice>(...);
// put into list
CinCout
  • 9,486
  • 12
  • 49
  • 67