Classes in D and C++

Lionello Lunesu lio at lunesu.remove.com
Sun Mar 4 23:32:09 PST 2007


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.



More information about the Digitalmars-d mailing list