Why delphi / pascal constructors can not be private as in C ++

3

Is there any reason why I can not leave a delphi constructor private?

    
asked by anonymous 09.04.2016 / 19:15

2 answers

1

Contrary to what you mentioned, you can declare a private constructor in Delphi. You 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, builders can be inherited. This does not happen in Java, C # or C ++ for example. Also, a class can have multiple constructors and they can also have different names. Generally called Create . But this is just a convention and not a rule.

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

Thus, it is easy to understand why all classes in Delphi have the parameterless constructor called Create .

If you need to hide the Create constructor already mentioned, try to answer one of the following questions in SOen:

link

link

link

Part of the answer is based on: link

    
27.04.2016 / 20:56
0

To be honest with you Delphi has yes Private methods for a constructor Yes, when a language is said to be Oriented it must follow the pillars of POO (Encapsulation, Abstraction, Inheritance and Polymorphism) I believe that for this you should declare before use

type Class declaration
...
Constructor Name; {Overload;}
...
end;
type Class declaration
...
Constructor Name(Arguments); {Overload;}
...
end;

I hope I've helped you at least a little bit: /

    
13.04.2016 / 02:54