I've got a problem with type casting from base class to derived (I'm casting because I'm sure that object is that exact type). here's my code (simplified):
class MyCollection
{
public:
Element* Get(int i) {
return elements[i];
}
void Add(Element* element) {
//finding i
elements[i] = element;
}
private:
Element* elements[100];
}
class Element {
public:
int ID;
}
class SpecialElement : public Element
{
public:
SpecialElement(char* name) {
this-> Name = name;
}
char* GetName() { return Name; }
private:
char* Name;
}
Now when I'm add to MyCollection object of SpecialElement when I put breakpoint at the moment of adding and cast my argument of Add method in Immediate Window and call GetName method it return me Name of object, but when I do something like this:
void main() {
MyCollection coll = new MyCollection();
coll.Add(new SpecialElement("MyName"));
SpecialElement* foundElement = (SpecialElement*)coll->Get(0);
foundElement->GetName(); //Error
}
I'm wondering why is that? Isn't founded object of type SpecialElement?