Classes in D and C++

Lionello Lunesu lio at lunesu.remove.com
Mon Mar 5 00:03:09 PST 2007


Bill Baxter wrote:
> Lionello Lunesu wrote:
>> Andy Little wrote:
>>> Hi all,
>>>
>>> I have been evaluating D over the last day in comparison to C++.
>>>
>>> The template metaprogramming stuff is great and I think its
>>  > a real improvement over C++.
>>>
>>> Sadly though theshowstopper for me is user defined types
>>  > ( classes). I was hoping that I could port my physical quantities
>>  > library to D, but the killer is the difference between classes in
>>  > D and C++.
>>>
>>> In C++ it is possible to create classes that act pretty much like
>>  > inbuilt types. I used this to good effect in my quan library.
>>>
>>> Unfortunately in D although you can do:
>>>
>>> class X{
>>>     this( int n_in){...}
>>> }
>>>
>>> Its not possible it seems to do e.g this:
>>>
>>> X  x(3);
>>>
>>> rather you have to do:
>>>
>>> X x = new X(3);
>>
>> Why don't you use "struct" instead? A struct can have functions, 
>> operator overloads, just no constructor/destructor/virtuals, but for 
>> simple types these shouldn't be needed. For custom types that behave 
>> as value types, you should be using a "struct" instead of a class.
>>
>> Instead of a constructor, create a "static opCall". opCall is the 
>> overload for "(..)" so you can instantiate your type similar to C++:
>>
>> struct SomeType {
>>   int member = 0;// default initializer here
>>   static SomeType opCall( int whatever ) {
>>     SomeType st;
>>     st.member = whatever;//custom initialize
>>     return st;
>>   }
>>   //...
>> }
>>
>> SomeType st = 2;//construction
>>
>> No need for constructors ;)
>>
>> L.
> 
> I don't think that quite works as you wrote.
> I think it needs to be
>    SomeType st = SomeType(2);
> or
>    auto st = SomeType(2);
> 
> if you want to avoid repeating your repeat-avoiding self repeatedly.
> 
> --bb

Actually, I was surprised myself, but it did work. And come to think of 
it, I remember Walter mentioning that he made it work, but I can't seem 
to find any reference to this in the changelog...

L.



More information about the Digitalmars-d mailing list