Search code examples
delphiclassparent

Parent class inside another class


Okay, so I have this class, let's say CMain, that contains a CFruit class. What I would like to do is run functions based on CFruit's type (if it's CPear or CApple, etc). So I'd like to do something like this:

type CMain = class
   myFruit : CFruit;
   function GetFruit() : CFruit;
   procedure SetFruit( Fruit : CFruit ); 
end;

procedure CMain.SetFruit( Fruit : CFruit );
begin
  if Fruit.IsPear then .. else etc;
end;

...obviously the compiler stops me from doing this because CFruit is just CPear and CApple's parent. Is there any viable way I can do this? (making sepparate CMain's is out of the question). Thanks.


Solution

  • Here is an example for the use of virtual methods:

    type 
    TFruit = class
    public
      procedure doSomethingFruitSpecific; virtual; abstract;
    end;
    
    TPear = class(TFruit)
    public
      procedure doSomethingFruitSpecific; override;
    end;
    
    TApple = class(TFruit)
    public
      procedure doSomethingFruitSpecific; override;
    end;
    
    TMain = class
       procedure SetFruit( Fruit : TFruit ); 
    end;
    
    implementation
    
    procedure TMain.SetFruit( Fruit : TFruit );
    begin
      Fruit.doSomethingFruitSpecific;
    end;
    
    procedure TApple.doSomethingFruitSpecific;
    begin
      Writeln('bake an apple pie');
    end;
    
    procedure TPear.doSomethingFruitSpecific;
    begin
      Writeln('pick some pears');
    end;