Object* o = dynamic_cast<GeometricalObject*>(it->Next());
you're casting to Object, so it should be: Object* o = dynamic_cast<Object*>(it->Next());
This tries to convert the pointer returned by it->Next() to a pointer of type Object* if *(it->Next()) is of type Object or else derived directly or indirectly from type Object (which seems to be true in your case).
Otherwise the expression evaluates to the nullpointer. So you could also replace line 31 with:
Thanks for the cast-info, that helped a lot.
By the way: I would like to Change line 31, because I want to read all objects of my Collection, isnĀ“t it?
what you need then is to range-loop or iterate through the Collection object:
1 2 3 4 5 6 7 8 9 10 11 12 13
//range-loops
for (auto& elem : *geoObjects)
//geoObjects is a pointer to Collection, so dereferencing it gives the Collection object
{
//...now elem gives access to each object within the Collection object
}
//(const) iterator
for (auto itr = (*geoObjects).cbegin(); itr != (*geoObjects).cend(); ++itr)
//assuming cbegin(), cend() etc are defined for Collection
{
//...now (*itr) fulfills the role of elem above
}
//Assume (it->Next()) returns a raw-pointer to GeometricalObject
std::unique_ptr<GeometricalObject> o_GeoObj = it->Next()//move, not copy, assignment;
std::unique_ptr<Object> o (dynamic_cast<Object*>(o_GeoObj.get()));// cast the embedded raw pointer
if(o)
{
o_GeoObj.release();//release object ownership transferred to o;
//... continue as before
}
//delete it;
/* may be required if NewIterator() returns raw pointer created with new operator
but if that is replaced also replaced with smart pointers then delete it not required */
IMO you shouldn't need any casting, that is why I mentioned polymorphism.
Tutorial wrote:
Pointers to base class
One of the key features of class inheritance is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and versatile feature.
tries to convert the pointer returned by it->Next() to a pointer of type Object* if *(it->Next()) is of type Object or else derived directly or indirectly from type Object (which seems to be true in your case).