- Home /
Have array of Unit; Unit is base Class; How to access derieved class functions???
Just as the question states... I need to gain scope to access functions in a derived class, or know if it is not possible??
Answer by karlhulme · Feb 23, 2014 at 11:20 PM
To access the functions of the derived class you need to cast your object. Hopefully the pretend methods below will illustrate the point. I've written this in c# as you didn't state a language preference. I've used an array, simply because you mention one in your question. Also, I've specified all types explicitly (rather than using var keyword) as it's hopefully clearer at this stage.
Assume a base class called Unit, and a class derived from this called SpecialisedUnit which defines the SpecialAction method.
// if you know unit is definitely of a derived type then do this...
void OperateOnUnits(Unit[] units)
{
foreach(Unit u in units)
{
((SpecialisedUnit)u).SpecialAction();
}
}
// if you don't know if unit is definitely of a derived type then do this…
void OperateOnUnits(Unit[] units)
{
foreach(Unit u in units)
{
SpecialisedUnit specialUnit = u as SpecialisedUnit;
if(specialUnit != null)
{
specialUnit.SpecialAction();
}
}
}
Peferctly, I knew I was going to need to cast them, but did not know the first thing how
if this was the info you were looking for, then please consider marking it as the answer. thanks :D