Access violation in trying to use a class

janderson askme at me.com
Mon May 28 15:28:56 PDT 2007


gerleim wrote:
> 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
> 

2 thoughts here:

1) If your running in debug it must be possible to query the debugging 
code to figure out where the error occured in code.

2) I think all error messages should come with a wiki page link.

-Joel



More information about the Digitalmars-d mailing list