Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting between parent and child classes in delphi

I'm writing some software that targets two versions of very similar hardware which, until I use the API to initialize the hardware I'm not able to know which type I'll be getting back.

Because the hardware is very similar I planned to have a parent class (TParent) that has some abstract methods (for where the hardware differs) and then two child classes (TChildA, TChildB) which implement those methods in a hardware dependent manner.

So I would first instantiate an object of TParent check what kind it is then cast it to the correct child.

However when I do this and call one of the abstract methods fully implemented in the child class I get an EAbstractError.

e.g:

myHardware:=TParent.Create();

if myHardware.TypeA then
   myHardware:=TChildA(myHardware)
else
   myHardware:=TChildB(myHardware);

myHardware.SomeMehtod();

I'm assuming that I can't cast a Parent Class to a child class, and also that there's probably a better way of doing this. Any pointers?

like image 679
RobS Avatar asked Dec 17 '22 08:12

RobS


1 Answers

You need a factory method to return you the correct class depending on the Type of hardware you are using...

function CreateHardware(isTypeA: Boolean): TParent;
begin
  if IsTypeA then Result := TChildA.Create
  else Result := TChildB.Create;
end;
...

var
  myHardware: TParent;
begin
  myHardware := CreateHardware(True);
  myHardwarde.SomeMethod;
end;

... or you could use the State pattern.

Common in either approach is that your TParent class does not has the knowledge to determine the type of hardware.That knowlegde is transfered into the factory method, caller of the factory method, factory itself or state class.

like image 120
Lieven Keersmaekers Avatar answered Dec 24 '22 00:12

Lieven Keersmaekers