deluvas
deluvas

Reputation: 379

Function returning class derivates

I have CObject as main class and CRock, CDesk, CComputer as derivates from CObject. I would like to write a function that reads a class enumeration (integer probably like OBJECT_COMPUTER) and returns the specific type.

Example:

function createObject( iType : Integer ) : CObject;
begin
  case iType of
    OBJECT_ROCK : Result := CRock.Create();
    OBJECT_DESK : Result := CDesk.Create(); 
  end;
end;

so I can use it like this: myRock := createObject( OBJECT_ROCK );

Now my problem is that the object returned is the main class parent and I can't use Rock functions on 'myRock' without type casting 'createObject( OBJECT_ROCK )' from CObject to CRock and I don't want to have 3 functions for each sub-class. Any ideas? Thanks in advance.

Upvotes: 1

Views: 832

Answers (2)

DX10
DX10

Reputation: 11

Like the previous example, but rather like this. We call it Inheritance, Polymorphism.

type
  TcObject = class
    procedure DoIt; virtual; abstract;
  end;

  TcRock = class(CObject)
    procedure DoIt; override;
  end;

  TcDesk = class(CObject)
    procedure DoIt; override;
  end;


var
  myRock: TcObject;
begin
  myRock := TcRock.Create;  //Inherits from TcObject and instantiate TcRock class.
  myRock.DoIt; //Will automaticall call TcRock.Doit --Polymorphism
  myRock.Free;
end;

Upvotes: 1

Sertac Akyuz
Sertac Akyuz

Reputation: 54802

If I understood correct, you'd declare a skeleton of derived functionality on the base class with abstract methods, then override and implement the method in each derived class.

type
  CObject = class
    procedure DoIt; virtual; abstract;
  end;
  CRock = class(CObject)
    procedure DoIt; override;
  end;
  CDesk = class(CObject)
    procedure DoIt; override;
  end;


var
  myRock: CObject;
begin
  myRock := createObject(OBJECT_ROCK);
  myRock.DoIt;
  myRock.Free;
end;

In the above example, 'DoIt' call on the 'myRock' instance would be correctly resolved to the method of that class.

If this is relevant at all read about abstract methods here.

Upvotes: 7

Related Questions