Why constructors in delphi/pascal cannot be private as they are in C++

Question:

Is there any reason why I can't leave a constructor in delphi private?

Answer:

Contrary to what you mentioned, you can declare a private constructor in Delphi. See, the code below just works:

program Project2;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Unit1 in 'Unit1.pas';

//var Foo: Tfoo2;
begin
  try
//    Foo := Tfoo2.CreatePrivado(1);
    TFoo2.FA := 'hello world';
    writeln(Foo.FA);
    readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

unit Unit1;

interface

type Tfoo2 = class(TObject)
     private
       constructor CreatePrivado(i:integer);
     public
       class var FA: string;
//       constructor Create(bar:Boolean);
     end;

implementation

uses
  SysUtils;

//constructor Tfoo2.Create(bar:Boolean);
//begin
//  inherited Create;
//  FA := 'bar';
//end;


constructor Tfoo2.CreatePrivado(i: integer);
begin
  inherited Create;
  FA := IntToStr(i);
end;

end.

In Delphi, constructors can be inherited. This doesn't happen in Java, C# or C++ for example. Also, a class can have multiple constructors and they can also have different names. Often called Create . But that's just a convention and not a rule.

Furthermore, all classes in Delphi ultimately inherit from the TObject class. This class contains a parameterless constructor called Create .

So it's easy to understand why all classes in Delphi have the parameterless constructor called Create .

If you need to hide the aforementioned Create builder, try an answer to one of the following questions in SOen:

https://stackoverflow.com/a/14003208/460775

https://stackoverflow.com/q/5392107/460775

https://stackoverflow.com/q/14003153/460775

Part of the answer is based on: http://www.yanniel.info/2011/08/hide-tobject-create-constructor-delphi.html

Scroll to Top
AllEscort