1

I have a vector of objects (DimensionItem) and I want to push another item to the vector. I only have a pointer to the object I wish to push. How can I get the object from the pointer.

(New to pointers, very possible I'm am fundamentally misunderstanding something)

DimensionItem *selected_Item = dynamic_cast<DimensionItem*>(g_items[i]); //g_items is a list of items taken from my scene

vector<DimensionItem> DimItems;
DimItems.push_back(selected_Item);

The error message is:

no matching function for call to 'std::vector::push_back(DimensionItem*&)'

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
seg
  • 31
  • 8

1 Answers1

3

You probably want:

DimensionItem& selected_Item = dynamic_cast<DimensionItem&>(*g_items[i]); // Throws if g_items[i] is not DimensionItem.
vector<DimensionItem> DimItems;
DimItems.push_back(selected_Item); // Stores a copy of selected_Item.

dynamic_cast<DimensionItem*>(g_items[i]) returns a null pointer if g_items[i] is not a DimensionItem, so the code would need to check the pointer for null before dereferencing it.

Whereas dynamic_cast<DimensionItem&>(*g_items[i]) throws an exception in that case.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271