I have such hierarchy of classes for saving entities found in DXF file:
class MyDxfItem {
public: DL_Attributes usedAttributes;
virtual ~MyDxfItem() {}
};
class MyDxfLayer : public MyDxfItem {
public:
MyDxfLayer(const std::string& name, int flags, bool off = false): LayerInfo(name,flags,off) {
}
public: DL_LayerData LayerInfo;
};
class MyDxfCircle : public MyDxfItem {
public:
MyDxfCircle(DL_CircleData inCircleInfo): circleInfo(inCircleInfo) {
}
public:
DL_CircleData circleInfo;
};
class MyDxfArc : public MyDxfItem {
public:
MyDxfArc(DL_ArcData inArcData) : arcInfo(inArcData) {
}
public: DL_ArcData arcInfo;
};
class MyDxfLine: public MyDxfItem {
public:
MyDxfLine(DL_LineData inLineData) : lineInfo(inLineData) {
}
public: DL_LineData lineInfo;
};
class MyDxfPoint : public MyDxfItem {
public: DL_PointData pointInfo;
};
class JovanDxfStruct
{
public: std::vector<MyDxfItem> MyListLayers;
public: std::vector<MyDxfItem> MyListItems;
} ;
extern JovanDxfStruct* globalPtrToDxfStruct;
MyDxfLayer is a subclass of MyDxfItem, MyDxfLayer expands and extends MyDxfItem. Base class has virtual destructor. I keep instances of MyDxfLayer in vector: std::vector<MyDxfItem> MyListLayers
, it is legal by inheritance.
Here is my code how I add item to this vector:
if (globalPtrToDxfStruct != nullptr) {
MyDxfLayer layerDataMy(data.name,data.flags, data.off);
layerDataMy.LayerInfo = data;
layerDataMy.usedAttributes = attributes;
globalPtrToDxfStruct->MyListLayers.push_back(layerDataMy);
}
I create here instance of MyDxfLayer and add it to std::vector. But when I try to downcast it back to its original class I get nullptr:
Right after the element was added to array it gets trimmed to baseclass and information stored in instance or derived class seems like lost.
Why is this happening? Why the code:
dynamic_cast<MyDxfLayer*>(&(globalPtrToDxfStruct->MyListLayers[0]))
returns null? you may see that globalPtrToDxfStruct->MyListLayers[0] is not null.
I am adding the instance of derived class to vector of instances of base classes.
I have referenced to example from https://en.wikipedia.org/wiki/Run-time_type_information#dynamic_cast_and_Java_cast , there is an example without vector, but I think it should be similar