D - Access violation in trying to use a class
- Niovol <niovol gmail.com> Apr 21 2007
- Derek Parnell <derek psych.ward> Apr 21 2007
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?
Apr 21 2007
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
Apr 21 2007








Derek Parnell <derek psych.ward>