00 Votes

Delphi/Lazarus: Class with different Create Methods

Question by Guest | 2013-11-15 at 11:57

I do not do programming for a long time and I've just dared creating my first class. For this, I have found a simple base frame on the Internet, which is working great.

The only problem is that I would like to write two different create methods for my class. Namely, it should be possible to create the class with different and various parameters.

Until now, it is only possible to me to program a single create method within my class. Is it even possible to create several create methods within one class or am I imagining something impossible?

ReplyPositiveNegative
2Best Answer2 Votes

This is no problem and readily possible.

As an example, here is a small class provding a simple counter.

unit MyCounterUnit;

interface

uses
  Classes, SysUtils;

type
  TMyCounter = class
  private
    FCounter: integer;
  protected
  public
    constructor Create; overload;
    constructor Create(AStartVal: integer); overload;
    destructor Destroy; override;
    procedure Increase;
  published
    property Counter: integer read FCounter;
  end;

implementation

constructor TMyCounter.Create;
begin
  inherited Create;
  self.FCounter:=0;
end;

constructor TMyCounter.Create(AStartVal: integer);
begin
  inherited Create;
  self.FCounter:=AStartVal;
end;

destructor TMyCounter.Destroy;
begin
  self.FCounter:=0;
  inherited Destroy;
end;

procedure TMyCounter.Increase;
begin
  inc(self.FCounter);
end;

As you can see, we are providing two different Create Methodes. Both can be used to create an instance of the class:

var
  Counter1, Counter2: TMyCounter;
begin
  // Variant 1 without start value
  Counter1:=TMyCounter.Create;
  Counter1.Increase;
  Counter1.Free;

  // Variant 2 with start value
  Counter2:=TMyCounter.Create(10);
  Counter2.Increase;
  Counter2.Free;
end;

When declaring multiple different Create Methods, it is important to write the key word "overload" behind the declaration. Otherwise, the declaration is just the same like declaring single Create Methods.
2013-11-17 at 18:26

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.