On Wednesday, 30 January 2013 at 14:48:07 UTC, Eko Wahyudin wrote:
Hi, guys? I'm new in D and I come from pascal. The constructor
concept is very different, and it's very confusing for me.
I want to create some statement in D which in pascal like this.
type
TMyObjectAClass = class of TMyObject_A; // number 1
TMyObject_A = class
constructor Create(AString : String);
end;
TMyObject_B = class(TMyObject_A)
constructor Create(AString : String); override;
end;
TMyObject_C = class(TMyObject_A)
end;
- - - - - - - - - - - - - - - - -
function Foo(AClass: TMyObjectAClass): TMyObject_A;
begin
Result:= AClass.Create(AClass.ClassName); //number 2
end;
- - - - - - - - - - - - - - - - -
var
B : TMyObject_B;
C : TMyObject_C;
begin
B:= Foo(TMyObject_B); //number 3
C:= Foo(TMyObject_C);
end.
===================================================================
Question 1> How I can make a data type "class of" in D language
Question 2> How to convert number 2, in D language.
Question 3> How I passing a "class type" as argument like number
3, and if D can do same thing like pascal, which one is called
by
D, TMyObject_A.Create() or TMyObject_B.Create() ? In pascal It
should be call TMyObject_B.Create() first
Thanks :)
Eko
There are no class types in D and classes without empty
constructors cannot be instantiated directly.
The closest solution is to use a templated function for Foo:
class TMyObject_A
{
this(string AString)
{ }
}
class TMyObject_B : TMyObject_A
{
this(string AString) { super(AString); }
}
class TMyObject_C : TMyObject_A
{
this(string AString) { super(AString); }
//there is no default constructor without parameters in the
base class.
}
TMyObjectAClass Foo(TMyObjectAClass)() if (is(TMyObjectAClass :
TMyObject_A))
{
return new TMyObjectAClass(TMyObjectAClass.stringof);
}
int main(string[] argv)
{
TMyObject_B B = Foo!TMyObject_B();
TMyObject_C C = Foo!TMyObject_C();
return 0;
}