This is just for learning purposes as I cannot seem to find such an answer any where else.. So I have multiple questions.. I won't do such a thing but I just want to know because my brain requires me to know or I'll be uncomfortable the rest of the day.
Assume I have the following classes:
class Control
{
//virtual stuff..
};
class Button : public Control
{
//More virtual stuff..
};
class CheckBox : public Control
{
//More virtual stuff..
};
Thus Button and CheckBox are sisters of the same mother Control.
Now assume someone curious like moi sees something like this:
std::vector<Control> ListOfControls; //Polymorphic Array.
ListOfControls.push_back(Button()); //Add Button to the Array.
ListOfControls.push_back(CheckBox()); //Add CheckBox to the Array.
How can I tell what datatypes that Array holds? How can I tell that ListOfControls[0] holds a Button and ListOfControls[1] holds a CheckBox? I read that you'd most likely have to do a dynamic cast and if it does not return null, it is that specific datatype:
if (dynamic_cast<Button*>(ListOfControls[0]) == ???) //I got lost.. :(
Another thing to get off my mind:
Assuming the same classes above, how do you tell for:
std::vector<void*> ListOfControls; //Polymorphic Array through Pointer.
ListOfControls.push_back(new Button()); //Add Button to the Array.
ListOfControls.push_back(new CheckBox()); //Add CheckBox to the Array.
Is there a way to do both the above examples without a dynamic cast or is there some sort of trick to get around it? I read that dynamic cast is usually never wanted..
Finally, can you down-cast from Parent to child?
Button Btn;
Control Cn;
Btn = (Button) Cn; //???