Thread overview
Access violation when using classes (beginner)
Jan 06, 2007
Robin Allen
Jan 06, 2007
Johan Granberg
Jan 06, 2007
Sean Kelly
Jan 06, 2007
Robin Allen
Jan 06, 2007
Mike Parker
January 06, 2007
Hi, could someone tell me why this code gives an access violation? It seems I must be missing some fundamental difference between C++ and D.

class C
{
    void zing() {}
}

void main()
{
    C c;
    c.zing();
}
January 06, 2007
Robin Allen wrote:

> Hi, could someone tell me why this code gives an access violation? It seems I must be missing some fundamental difference between C++ and D.
> 
> class C
> {
>     void zing() {}
> }
> 
> void main()
> {
>     C c;
>     c.zing();
> }

Yes :)

classes are reference types so the current value of c is null. To initialize c change "C c;" into "C c=new C()".
January 06, 2007
Robin Allen wrote:
> Hi, could someone tell me why this code gives an access violation? It seems I
> must be missing some fundamental difference between C++ and D.
> 
> class C
> {
>     void zing() {}
> }
> 
> void main()
> {
>     C c;
>     c.zing();
> }

Using objects in D is similar to using them in Java in that objects are reference-based.  Try:

    void main()
    {
        // Will be collected by the GC at some point after c goes
        // out of scope.
        C c = new C();
        c.zing();

        // Will be destroyed automatically the moment d goes out of
        // scope.  The class instance may be allocated on the stack
        // but is not required to be.
        scope C d = new C();
        d.zing();
    }


Sean
January 06, 2007
Ah, so you only ever work with references, and you always use new. Thanks to both of you.
January 06, 2007
Robin Allen wrote:
> Ah, so you only ever work with references, and you always use new. Thanks to both
> of you.

When dealing with classes, yes. But not with structs, which are value types. So this:

MyStruct c;
c.someFunc();

actually works, since struct instances are not references.