digitalmars.D.learn - Access violation when using classes (beginner)
- Robin Allen <r.a3 ntlworld.com> Jan 05 2007
- Johan Granberg <lijat.meREM OVE.gmail.com> Jan 05 2007
- Sean Kelly <sean f4.ca> Jan 05 2007
- Robin Allen <r.a3 ntlworld.com> Jan 05 2007
- Mike Parker <aldacron71 yahoo.com> Jan 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();
}
Jan 05 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()".
Jan 05 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
Jan 05 2007
Ah, so you only ever work with references, and you always use new. Thanks to both of you.
Jan 05 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.
Jan 06 2007









Johan Granberg <lijat.meREM OVE.gmail.com> 