www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Access violation when using classes (beginner)

reply Robin Allen <r.a3 ntlworld.com> writes:
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();
}
Jan 05 2007
next sibling parent Johan Granberg <lijat.meREM OVE.gmail.com> writes:
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()".
Jan 05 2007
prev sibling parent reply Sean Kelly <sean f4.ca> writes:
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
Jan 05 2007
parent reply Robin Allen <r.a3 ntlworld.com> writes:
Ah, so you only ever work with references, and you always use new. Thanks to
both
of you.
Jan 05 2007
parent Mike Parker <aldacron71 yahoo.com> writes:
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.
Jan 06 2007