Class Access In D

closed account (zb0S216C)
In D, I created a class called MyClass with a sub-class called Data. In main, I created an instance of MyClass. There're two problems with my code: 1) Cannot access the member of the sub-class. 2) Cannot use the constructor when the instance to MyClass is created.

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class MyClass
{
    public:

        this( int Init = 0 )
        {
            IntMember = Init;
        }

        class Data
        {
            int Member = 0;
        }

        int Variable = 0;

    protected:

        int IntMember = 0;
}

int main(  )
{
    MyClass Class( 4 );     // Error 1) no property 'opCall' for type 'hello.MyClass'
    Class.Variable = 9;     // This is fine.
    Class.Data.Member = 5;  // Error 2) 'this' is only defined in non-static member functions, not main

    return 0;
}


Error: 1
I've tried removing the parentheses from round the constructor and it removes the error. So how do I use the defined constructor in MyClass?

Error: 2
I've tried using the this keyword but give me the same error.
Last edited on
You know this is a C++ forum, right?
closed account (zb0S216C)
Yes, I know that. D is based on C.
1
2
3
4
        class Data
        {
            int Member = 0;
        }
Isn't Member private?

Edit:
http://www.digitalmars.com/d/2.0/class.html#nested
I think that you never create a instance of Data, you just declare the class.
1
2
MyClass Class(4);
MyClass.Data foo = new Class.Data; //foo is linked to Class 
Last edited on
AFAIK you have to do this:
MyClass Class=new Class(4);
Last edited on
closed account (zb0S216C)
I think that you never create a instance of Data, you just declare the class.

That fixed the second error :)

AFAIK you have to do this: MyClass Class=new Class(4);

That fixed the first error :)

However, I have an Access Violation when accessing Member in Data:
1
2
3
4
5
6
7
8
9
class Data
{
    public:
        int Member = 0; 
} Data data;

//...

data.Member = 1;  // Access violation.  
Topic archived. No new replies allowed.