Access violation in trying to use a class

gerleim elf_qt at _deletethisidyouarenotaspammer_yahoo.com
Mon May 28 14:23:17 PDT 2007


Wow, but the message is silly.
And hard to find - no file name and line number!
Just "Error: Access Violation".

It still works like this in version 7.51 Build 020.

Why the compiler does not give a decent error on this?

Sorry if it's something that is discussed, but I'm coming back to D after a long
pause.

gerleim
(ElfQT in the past)

== Repost the article of Derek Parnell (derek at psych.ward)
== Posted at 2007/04/21 09:07 to D

On Sat, 21 Apr 2007 12:46:14 +0000 (UTC), Niovol wrote:

> I have written following code:
> ---------------------------
> import std.stdio;
> class Abc
> {
> public:
>  int add(int a, int b) { return a + b; }
> }
> void main()
> {
>  Abc abc;
>  int a = abc.add(1, 2);
> }
> ----------------------------
> Upon compilling and building I executed a program. The message
> appeared: "Error: Access Violation". What should I do to use
> classes?

Firstly, this newsgroup is o longer active. Please use the group
"digitalmars.D" next time.

But back to your problem. Unlike C++, D requires that all classes be
instantiated before use. That means, you must use a 'new' statement on your
object before trying to access it. In D, a simple declaration such as your

  Abc abc;

only allocates space for a null reference.

This should work ...

 import std.stdio;
 class Abc
 {
 public:
  int add(int a, int b) { return a + b; }
 }
 void main()
 {
  Abc abc = new Abc; // Must be instantiated before use.
  int a = abc.add(1, 2);

        Abc def;
        int b;
        def = new Abc;  // 'new' before use.
  b = abc.add(3, 4);

 }


--

Derek Parnell
Melbourne, Australia
"Justice for David Hicks!"
skype: derek.j.parnell




More information about the Digitalmars-d mailing list