Say I have an base struct Action
:
struct Action
{
int type;
virtual void print() { }
}
And 2 derived structs A1, A2
:
struct A1 : Action
{
A1 : Action(0) { }
void print() { cout << "A1"; }
}
struct A2 : Action
{
A2 : Action(1) { }
void print() { cout << "A2"; }
}
Then in my main function I have a stack:
stack<Action> actions;
A1 a1;
A2 a2;
actions.push(a1);
actions.push(a2);
while(!actions.empty())
{
Action element = actions.top();
element.print();
actions.pop();
}
However, the print()
function will always call the base class print()
, instead of the derived class. How do I get it to refer to the derived class instead?
In C# I understand there is a GetType()
function, but is there a similar thing in c++?
Edit: Specifically I am looking for a way to collect all objects of a similar base class into a single container, so that I can iterate through all of them, without losing information of a derived class.
Something along the lines of (in C#):
if(element.getType() == typeof(A1))
((A1)element).print();
else if (element.getType() == typeof(A2))
((A2)element).print();