digitalmars.D.learn - Access violation when using classes (beginner)
- Robin Allen (11/11) Jan 05 2007 Hi, could someone tell me why this code gives an access violation? It se...
- Johan Granberg (4/17) Jan 05 2007 Yes :)
- Sean Kelly (16/29) Jan 05 2007 Using objects in D is similar to using them in Java in that objects are
- Robin Allen (2/2) Jan 05 2007 Ah, so you only ever work with references, and you always use new. Thank...
- Mike Parker (6/8) Jan 06 2007 When dealing with classes, yes. But not with structs, which are value
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> 