Classes or stucts :: Newbie

Joost 't Hart Joost.t.Hart at planet.nl
Sun Dec 19 12:42:49 PST 2010


On 12/20/2010 04:00 PM, David Currie wrote:

> I am new to D (like many have done C++ , Java ).

Me too. Let's see what we can figure out together :-)

>
> Can a class be instantiated on the stack ?
>
> eg
>
> class C
> {
> private int _I1;
> private int _I2;
>
> public:
>
> this(int pI) // constructor
> {
> _I1 = pI;
> _I2 = pI + 1;
> }
>
> // ... other methods etc
> }
>
> void f() // just a function
> {
>
> C myC(3); // C++ syntax BUT is there a d equivalent
>
> }
>
> It appears that D ASSUMES myC is really a myC*(in C++)

It is not so much a *, but reference semantics (like T& param in C++).

>
> and therefore requires
>
> C myC = new C(3);
> // but this ALWAYS requires calling the memory allocator
> // this is what Java does (forces your Class instance onto the Heap)
>
> Is there any way in D to instantiate a stack object ?

Not a class object. Only values are on the stack. The reference 
semantics requires a "living" entity to refer to.

>
> Will a struct do?

Yes, if you so wish, but new also works. Structs have value semantics.

>
> Does a struct have a constructor (as opposed to an opcall?)

You can define one, but you cannot redefine the default this() 
constructor. Because structs have value semantics, D wants to make sure 
that T.init member values are slotted in by default. Note that T.init 
for a class type is the null reference.

>
> I would be very grateful for a response.

Hope this helps a bit.
Cheers,
Joost.

>
> David Currie
>
>



More information about the Digitalmars-d-learn mailing list