Thread overview | |||||||
---|---|---|---|---|---|---|---|
|
January 06, 2007 Access violation when using classes (beginner) | ||||
---|---|---|---|---|
| ||||
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 Re: Access violation when using classes (beginner) | ||||
---|---|---|---|---|
| ||||
Posted in reply to Robin Allen | 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 Re: Access violation when using classes (beginner) | ||||
---|---|---|---|---|
| ||||
Posted in reply to Robin Allen | 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 Re: Access violation when using classes (beginner) | ||||
---|---|---|---|---|
| ||||
Posted in reply to Sean Kelly | Ah, so you only ever work with references, and you always use new. Thanks to both of you. |
January 06, 2007 Re: Access violation when using classes (beginner) | ||||
---|---|---|---|---|
| ||||
Posted in reply to Robin Allen | 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.
|
Copyright © 1999-2021 by the D Language Foundation